Skip to content

Commit c932c99

Browse files
Added code of Twos Complement
1 parent edc0838 commit c932c99

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import java.util.Scanner;
4+
5+
public class TwosComplement {
6+
7+
// Function to get the 2's complement of a binary number
8+
public static String twosComplement(String binary) {
9+
StringBuilder onesComplement = new StringBuilder();
10+
11+
// Step 1: Find the 1's complement (invert the bits)
12+
for (int i = 0; i < binary.length(); i++) {
13+
if (binary.charAt(i) == '0') {
14+
onesComplement.append('1');
15+
} else {
16+
onesComplement.append('0');
17+
}
18+
}
19+
20+
// Step 2: Add 1 to the 1's complement
21+
StringBuilder twosComplement = new StringBuilder(onesComplement);
22+
boolean carry = true;
23+
for (int i = onesComplement.length() - 1; i >= 0; i--) {
24+
if (onesComplement.charAt(i) == '1' && carry) {
25+
twosComplement.setCharAt(i, '0');
26+
} else if (onesComplement.charAt(i) == '0' && carry) {
27+
twosComplement.setCharAt(i, '1');
28+
carry = false;
29+
}
30+
}
31+
32+
// If there is still a carry, append '1' at the beginning
33+
if (carry) {
34+
twosComplement.insert(0, '1');
35+
}
36+
37+
return twosComplement.toString();
38+
}
39+
40+
public static void main(String[] args) {
41+
Scanner scanner = new Scanner(System.in);
42+
43+
// Input a binary number
44+
System.out.print("Enter a number: ");
45+
int n = scanner.nextInt();
46+
String binary = Integer.toBinaryString(n);
47+
48+
// Compute and print the 2's complement
49+
String result = twosComplement(binary);
50+
int num = Integer.parseInt(result, 2);
51+
System.out.println("2's complement of " + n +"("+binary+")" +" is: " + num + "("+ result+")");
52+
53+
scanner.close();
54+
}
55+
}

0 commit comments

Comments
 (0)