-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathOnesComplement.java
More file actions
28 lines (26 loc) · 928 Bytes
/
OnesComplement.java
File metadata and controls
28 lines (26 loc) · 928 Bytes
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
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();
}
}