package com.thealgorithms.bitmanipulation;
public final class TwosComplement {
private TwosComplement() {
}
public static String twosComplement(String binary) {
StringBuilder onesComplement = new StringBuilder();
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '0') {
onesComplement.append('1');
} else {
onesComplement.append('0');
}
}
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 (carry) {
twosComplement.insert(0, '1');
}
return twosComplement.toString();
}
}