Skip to content

Commit ddb8a06

Browse files
Added Twos Complement
1 parent e285e02 commit ddb8a06

File tree

1 file changed

+6
-20
lines changed

1 file changed

+6
-20
lines changed

src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package com.thealgorithms.bitmanipulation;
2-
3-
import java.util.Scanner;
4-
2+
/**
3+
* @wikipedia - https://en.wikipedia.org/wiki/Two%27s_complement
4+
* This Algorithm was first suggested by Jon Von Neumann
5+
* @author - https://github.com/Monk-AbhinayVerma
6+
* @return - class returns the two's complement of any binary number
7+
*/
58
public class TwosComplement {
6-
79
// Function to get the 2's complement of a binary number
810
public static String twosComplement(String binary) {
911
StringBuilder onesComplement = new StringBuilder();
@@ -36,20 +38,4 @@ public static String twosComplement(String binary) {
3638

3739
return twosComplement.toString();
3840
}
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-
}
5541
}

0 commit comments

Comments
 (0)