Skip to content

Added code of Ones & Twos Complement in BitManipulation #5604

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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();
}
}
Original file line number Diff line number Diff line change
@@ -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();
}
}