Repository: TheAlgorithms/Java
Pull request #5604 (2024-10-06 06:59:18)

Added code of Ones & Twos Complement in BitManipulation
<!--
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/5604?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `0%` with `42 lines` in your changes missing coverage. Please review.
> Project coverage is 54.46%. Comparing base [(`07cb6c4`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/07cb6c46a8d3b46d6b32c84e23da50ac8fecd30e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`c932c99`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/c932c99512f83ef1a8eb6c80e3caed98025aa16e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).
> Report is 1 commits behind head on master.

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5604?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [.../thealgorithms/bitmanipulation/TwosComplement.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5604?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fbitmanipulation%2FTwosComplement.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9iaXRtYW5pcHVsYXRpb24vVHdvc0NvbXBsZW1lbnQuamF2YQ==) | 0.00% | [26 Missing :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5604?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |
| [.../thealgorithms/bitmanipulation/OnesComplement.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5604?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fbitmanipulation%2FOnesComplement.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9iaXRtYW5pcHVsYXRpb24vT25lc0NvbXBsZW1lbnQuamF2YQ==) | 0.00% | [16 Missing :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5604?src=pr&el=tree&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    #5604      +/-   ##
============================================
- Coverage     54.60%   54.46%   -0.15%     
- Complexity     3417     3438      +21     
============================================
  Files           536      539       +3     
  Lines         15406    15573     +167     
  Branches       2937     2959      +22     
============================================
+ Hits           8413     8482      +69     
- Misses         6638     6735      +97     
- Partials        355      356       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5604?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).

Monk-AbhinayVerma: I have added tests, please review

Patch:
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java b/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java
new file mode 100644
index 00000000..c5c06842
--- /dev/null
+++ b/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java
@@ -0,0 +1,28 @@
+package com.thealgorithms.bitmanipulation;
+
+/**
+ * @author - https://github.com/Monk-AbhinayVerma
+ * @Wikipedia - https://en.wikipedia.org/wiki/Ones%27_complement
+ *            The class OnesComplement computes the complement of binary number
+ *            and returns
+ *            the complemented binary string.
+ * @return the complimented binary string
+ */
+public final class OnesComplement {
+    private OnesComplement() {
+    }
+
+    // Function to get the 1's complement of a binary number
+    public static String onesComplement(String binary) {
+        StringBuilder complement = new StringBuilder();
+        // Invert each bit to get the 1's complement
+        for (int i = 0; i < binary.length(); i++) {
+            if (binary.charAt(i) == '0') {
+                complement.append('1');
+            } else {
+                complement.append('0');
+            }
+        }
+        return complement.toString();
+    }
+}
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java b/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java
new file mode 100644
index 00000000..0bc20072
--- /dev/null
+++ b/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java
@@ -0,0 +1,41 @@
+package com.thealgorithms.bitmanipulation;
+
+/**
+ * @wikipedia - https://en.wikipedia.org/wiki/Two%27s_complement
+ *            This Algorithm was first suggested by Jon Von Neumann
+ * @author - https://github.com/Monk-AbhinayVerma
+ * @return the two's complement of any binary number
+ */
+public final class TwosComplement {
+    private TwosComplement() {
+    }
+
+    // Function to get the 2's complement of a binary number
+    public static String twosComplement(String binary) {
+        StringBuilder onesComplement = new StringBuilder();
+        // Step 1: Find the 1's complement (invert the bits)
+        for (int i = 0; i < binary.length(); i++) {
+            if (binary.charAt(i) == '0') {
+                onesComplement.append('1');
+            } else {
+                onesComplement.append('0');
+            }
+        }
+        // Step 2: Add 1 to the 1's complement
+        StringBuilder twosComplement = new StringBuilder(onesComplement);
+        boolean carry = true;
+        for (int i = onesComplement.length() - 1; i >= 0; i--) {
+            if (onesComplement.charAt(i) == '1' && carry) {
+                twosComplement.setCharAt(i, '0');
+            } else if (onesComplement.charAt(i) == '0' && carry) {
+                twosComplement.setCharAt(i, '1');
+                carry = false;
+            }
+        }
+        // If there is still a carry, append '1' at the beginning
+        if (carry) {
+            twosComplement.insert(0, '1');
+        }
+        return twosComplement.toString();
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java b/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java
new file mode 100644
index 00000000..6be4eb59
--- /dev/null
+++ b/src/test/java/com/thealgorithms/bitmanipulation/OnesComplementTest.java
@@ -0,0 +1,47 @@
+package com.thealgorithms.bitmanipulation;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test case for Highest Set Bit
+ * @author Abhinay Verma(https://github.com/Monk-AbhinayVerma)
+ */
+public class OnesComplementTest {
+
+    @Test
+    public void testOnesComplementAllZeroes() {
+
+        // Test cases with all-zero binary strings
+        assertEquals("1111", OnesComplement.onesComplement("0000"));
+        assertEquals("111", OnesComplement.onesComplement("000"));
+        assertEquals("11", OnesComplement.onesComplement("00"));
+        assertEquals("1", OnesComplement.onesComplement("0"));
+    }
+
+    @Test
+    public void testOnesComplementAllOnes() {
+        // Test cases with all-one binary strings
+        assertEquals("0000", OnesComplement.onesComplement("1111"));
+        assertEquals("000", OnesComplement.onesComplement("111"));
+        assertEquals("00", OnesComplement.onesComplement("11"));
+        assertEquals("0", OnesComplement.onesComplement("1"));
+    }
+
+    @Test
+    public void testOnesComplementMixedBits() {
+        // Test more mixed binary patterns
+        assertEquals("1010", OnesComplement.onesComplement("0101"));
+        assertEquals("0101", OnesComplement.onesComplement("1010"));
+        assertEquals("1100", OnesComplement.onesComplement("0011"));
+        assertEquals("0011", OnesComplement.onesComplement("1100"));
+        assertEquals("1001", OnesComplement.onesComplement("0110"));
+    }
+
+    @Test
+    public void testOnesComplementEmptyString() {
+        // Test empty string scenario
+        assertEquals("", OnesComplement.onesComplement(""));
+    }
+}
diff --git a/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java b/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java
new file mode 100644
index 00000000..512e94b6
--- /dev/null
+++ b/src/test/java/com/thealgorithms/bitmanipulation/TwosComplementTest.java
@@ -0,0 +1,54 @@
+package com.thealgorithms.bitmanipulation;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test case for Highest Set Bit
+ * @author Abhinay Verma(https://github.com/Monk-AbhinayVerma)
+ */
+public class TwosComplementTest {
+
+    @Test
+    public void testTwosComplementAllZeroes() {
+        // Test with a binary number consisting entirely of zeroes
+        assertEquals("10000", TwosComplement.twosComplement("0000"));
+        assertEquals("1000", TwosComplement.twosComplement("000"));
+        assertEquals("100", TwosComplement.twosComplement("00"));
+        assertEquals("10", TwosComplement.twosComplement("0"));
+    }
+
+    @Test
+    public void testTwosComplementAllOnes() {
+        // Test with a binary number consisting entirely of ones
+        assertEquals("00001", TwosComplement.twosComplement("11111"));
+        assertEquals("0001", TwosComplement.twosComplement("1111"));
+        assertEquals("001", TwosComplement.twosComplement("111"));
+        assertEquals("01", TwosComplement.twosComplement("11"));
+    }
+
+    @Test
+    public void testTwosComplementMixedBits() {
+        // Test with binary numbers with mixed bits
+        assertEquals("1111", TwosComplement.twosComplement("0001")); // 1's complement: 1110, then add 1: 1111
+        assertEquals("1001", TwosComplement.twosComplement("0111")); // 1's complement: 1000
+        assertEquals("11001", TwosComplement.twosComplement("00111")); // 1's complement: 11000, add 1: 11001
+        assertEquals("011", TwosComplement.twosComplement("101")); // 1's complement: 010, add 1: 011
+    }
+
+    @Test
+    public void testTwosComplementSingleBit() {
+        // Test with single bit
+        assertEquals("10", TwosComplement.twosComplement("0"));
+        assertEquals("1", TwosComplement.twosComplement("1"));
+    }
+
+    @Test
+    public void testTwosComplementWithLeadingZeroes() {
+        // Test with leading zeroes in the input
+        assertEquals("1111", TwosComplement.twosComplement("0001"));
+        assertEquals("101", TwosComplement.twosComplement("011"));
+        assertEquals("110", TwosComplement.twosComplement("010"));
+    }
+}