Repository: TheAlgorithms/Java
Pull request #5338 (2024-08-17 09:56:32)

refactor: `BinaryToOctal`
Improving the code to make it more readable.
Adding additional tests to this algorithm.

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5338?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 42.89%. Comparing base [(`7c58b19`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/7c58b190c8ebd375cb87f873e0acfdc21282d7e8?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`7f9b214`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/7f9b21408dbb0a16df74ed4cf1d3fd38e04b2e9d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5338      +/-   ##
============================================
+ Coverage     42.87%   42.89%   +0.02%     
- Complexity     2661     2664       +3     
============================================
  Files           522      522              
  Lines         15483    15478       -5     
  Branches       2950     2950              
============================================
+ Hits           6638     6640       +2     
+ Misses         8560     8554       -6     
+ Partials        285      284       -1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5338?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java b/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java
index 6fef0902..5407c852 100644
--- a/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java
+++ b/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java
@@ -1,27 +1,11 @@
 package com.thealgorithms.conversions;
 
-import java.util.Scanner;
-
-/**
- * Converts any Binary number to an Octal Number
- *
- * @author Zachary Jones
- */
 public final class BinaryToOctal {
-    private BinaryToOctal() {
-    }
+    private static final int BITS_PER_OCTAL_DIGIT = 3;
+    private static final int BINARY_BASE = 2;
+    private static final int DECIMAL_BASE = 10;
 
-    /**
-     * Main method
-     *
-     * @param args Command line arguments
-     */
-    public static void main(String[] args) {
-        Scanner sc = new Scanner(System.in);
-        System.out.println("Input the binary number: ");
-        int b = sc.nextInt();
-        System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
-        sc.close();
+    private BinaryToOctal() {
     }
 
     /**
@@ -29,22 +13,33 @@ public final class BinaryToOctal {
      *
      * @param binary The binary number
      * @return The octal number
+     * @throws IllegalArgumentException if the input is not a valid binary number
      */
     public static String convertBinaryToOctal(int binary) {
-        String octal = "";
-        int currBit = 0;
-        int j = 1;
+        if (binary == 0) {
+            return "0";
+        }
+
+        if (!String.valueOf(binary).matches("[01]+")) {
+            throw new IllegalArgumentException("Input is not a valid binary number.");
+        }
+
+        StringBuilder octal = new StringBuilder();
+        int currentBit;
+        int bitValueMultiplier = 1;
+
         while (binary != 0) {
-            int code3 = 0;
-            for (int i = 0; i < 3; i++) {
-                currBit = binary % 10;
-                binary = binary / 10;
-                code3 += currBit * j;
-                j *= 2;
+            int octalDigit = 0;
+            for (int i = 0; i < BITS_PER_OCTAL_DIGIT && binary != 0; i++) {
+                currentBit = binary % DECIMAL_BASE;
+                binary /= DECIMAL_BASE;
+                octalDigit += currentBit * bitValueMultiplier;
+                bitValueMultiplier *= BINARY_BASE;
             }
-            octal = code3 + octal;
-            j = 1;
+            octal.insert(0, octalDigit);
+            bitValueMultiplier = 1; // Reset multiplier for the next group
         }
-        return octal;
+
+        return octal.toString();
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java b/src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java
index c7018dae..98bd55a3 100644
--- a/src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java
+++ b/src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java
@@ -1,14 +1,24 @@
 package com.thealgorithms.conversions;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
 
 public class BinaryToOctalTest {
 
+    @ParameterizedTest
+    @CsvSource({"0, 0", "1, 1", "10, 2", "111, 7", "1000, 10", "1111, 17", "110101, 65", "1010101, 125", "110110011, 663", "111111111, 777", "10010110, 226", "1011101, 135"})
+    void testConvertBinaryToOctal(int binary, String expectedOctal) {
+        assertEquals(expectedOctal, BinaryToOctal.convertBinaryToOctal(binary));
+    }
+
     @Test
-    public void testBinaryToOctal() {
-        assertEquals("226", BinaryToOctal.convertBinaryToOctal(10010110));
-        assertEquals("135", BinaryToOctal.convertBinaryToOctal(1011101));
+    void testIncorrectInput() {
+        assertThrows(IllegalArgumentException.class, () -> BinaryToOctal.convertBinaryToOctal(1234));
+        assertThrows(IllegalArgumentException.class, () -> BinaryToOctal.convertBinaryToOctal(102));
+        assertThrows(IllegalArgumentException.class, () -> BinaryToOctal.convertBinaryToOctal(-1010));
     }
 }