- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathOnesComplement.java
28 lines (26 loc) · 928 Bytes
/
OnesComplement.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
packagecom.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
*/
publicfinalclassOnesComplement {
privateOnesComplement() {
}
// Function to get the 1's complement of a binary number
publicstaticStringonesComplement(Stringbinary) {
StringBuildercomplement = newStringBuilder();
// Invert each bit to get the 1's complement
for (inti = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '0') {
complement.append('1');
} else {
complement.append('0');
}
}
returncomplement.toString();
}
}