Repository: TheAlgorithms/Java
Pull request #5593 (2024-10-06 05:04:43)

feat: Binary addition algorithm added
<!--
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/5593?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 54.62%. Comparing base [(`f34fe4d`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/f34fe4d8408ac35cef900cfae022ffadfc007ea3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`e623c9b`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/e623c9b99b742b8d4aaafdf982a0d42cf6151283?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    #5593      +/-   ##
============================================
+ Coverage     54.56%   54.62%   +0.06%     
- Complexity     3413     3426      +13     
============================================
  Files           535      536       +1     
  Lines         15383    15412      +29     
  Branches       2935     2945      +10     
============================================
+ Hits           8393     8419      +26     
- Misses         6637     6638       +1     
- Partials        353      355       +2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5593?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/DIRECTORY.md b/DIRECTORY.md
index 19ebe5c4..2b4dc078 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -272,6 +272,7 @@
             * [GrahamScan](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/geometry/GrahamScan.java)
           * greedyalgorithms
             * [ActivitySelection](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java)
+            * [BinaryAddition](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java)
             * [CoinChange](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java)
             * [DigitSeparation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/DigitSeparation.java)
             * [FractionalKnapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java)
@@ -787,6 +788,7 @@
             * [GrahamScanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java)
           * greedyalgorithms
             * [ActivitySelectionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java)
+            * [BinaryAdditionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java)
             * [CoinChangeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java)
             * [DigitSeparationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/DigitSeparationTest.java)
             * [FractionalKnapsackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackTest.java)
diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java b/src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java
new file mode 100644
index 00000000..074c76b9
--- /dev/null
+++ b/src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java
@@ -0,0 +1,75 @@
+package com.thealgorithms.greedyalgorithms;
+
+import java.util.Collections;
+
+/**
+ * BinaryAddition class to perform binary addition of two binary strings.
+ */
+public class BinaryAddition {
+    /**
+     * Computes the sum of two binary characters and a carry.
+     * @param a First binary character ('0' or '1').
+     * @param b Second binary character ('0' or '1').
+     * @param carry The carry from the previous operation ('0' or '1').
+     * @return The sum as a binary character ('0' or '1').
+     */
+    public char sum(char a, char b, char carry) {
+        int count = 0;
+        if (a == '1') {
+            count++;
+        }
+        if (b == '1') {
+            count++;
+        }
+        if (carry == '1') {
+            count++;
+        }
+        return count % 2 == 0 ? '0' : '1';
+    }
+    /**
+     * Computes the carry for the next higher bit from two binary characters and a carry.
+     * @param a First binary character ('0' or '1').
+     * @param b Second binary character ('0' or '1').
+     * @param carry The carry from the previous operation ('0' or '1').
+     * @return The carry for the next bit ('0' or '1').
+     */
+    public char carry(char a, char b, char carry) {
+        int count = 0;
+        if (a == '1') {
+            count++;
+        }
+        if (b == '1') {
+            count++;
+        }
+        if (carry == '1') {
+            count++;
+        }
+        return count >= 2 ? '1' : '0';
+    }
+    /**
+     * Adds two binary strings and returns their sum as a binary string.
+     * @param a First binary string.
+     * @param b Second binary string.
+     * @return Binary string representing the sum of the two binary inputs.
+     */
+    public String addBinary(String a, String b) {
+        // Padding the shorter string with leading zeros
+        int maxLength = Math.max(a.length(), b.length());
+        a = String.join("", Collections.nCopies(maxLength - a.length(), "0")) + a;
+        b = String.join("", Collections.nCopies(maxLength - b.length(), "0")) + b;
+        StringBuilder result = new StringBuilder();
+        char carry = '0';
+        // Iterating over the binary strings from the least significant to the most significant bit
+        for (int i = maxLength - 1; i >= 0; i--) {
+            char sum = sum(a.charAt(i), b.charAt(i), carry);
+            carry = carry(a.charAt(i), b.charAt(i), carry);
+            result.append(sum);
+        }
+        // If there's a remaining carry, append it
+        if (carry == '1') {
+            result.append('1');
+        }
+        // Reverse the result as we constructed it from the least significant bit
+        return result.reverse().toString();
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java
new file mode 100644
index 00000000..893ca02e
--- /dev/null
+++ b/src/test/java/com/thealgorithms/greedyalgorithms/BinaryAdditionTest.java
@@ -0,0 +1,96 @@
+package com.thealgorithms.greedyalgorithms;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class BinaryAdditionTest {
+
+    BinaryAddition binaryAddition = new BinaryAddition();
+
+    @Test
+    public void testEqualLengthNoCarry() {
+        String a = "1010";
+        String b = "1101";
+        String expected = "10111";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+
+    @Test
+    public void testEqualLengthWithCarry() {
+        String a = "1111";
+        String b = "1111";
+        String expected = "11110";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+
+    @Test
+    public void testDifferentLengths() {
+        String a = "101";
+        String b = "11";
+        String expected = "1000";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+
+    @Test
+    public void testAllZeros() {
+        String a = "0";
+        String b = "0";
+        String expected = "0";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+
+    @Test
+    public void testAllOnes() {
+        String a = "1111";
+        String b = "1111";
+        String expected = "11110";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+
+    @Test
+    public void testOneZeroString() {
+        String a = "0";
+        String b = "10101";
+        String expected = "10101";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+
+        // Test the other way around
+        a = "10101";
+        b = "0";
+        expected = "10101";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+
+    @Test
+    public void testLargeBinaryNumbers() {
+        String a = "101010101010101010101010101010";
+        String b = "110110110110110110110110110110";
+        String expected = "1100001100001100001100001100000";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+
+    @Test
+    public void testOneMuchLonger() {
+        String a = "1";
+        String b = "11111111";
+        String expected = "100000000";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+
+    @Test
+    public void testEmptyStrings() {
+        String a = "";
+        String b = "";
+        String expected = ""; // Adding two empty strings should return 0
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+
+    @Test
+    public void testAlternatingBits() {
+        String a = "10101010";
+        String b = "01010101";
+        String expected = "11111111";
+        assertEquals(expected, binaryAddition.addBinary(a, b));
+    }
+}