File tree 1 file changed +39
-0
lines changed
src/main/java/com/thealgorithms/bitmanipulation 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .thealgorithms .bitmanipulation ;
2
+
3
+ import java .util .Scanner ;
4
+
5
+ public class OnesComplement {
6
+
7
+ // Function to get the 1's complement of a binary number
8
+ public static String onesComplement (String binary ) {
9
+ StringBuilder complement = new StringBuilder ();
10
+
11
+ // Invert each bit to get the 1's complement
12
+ for (int i = 0 ; i < binary .length (); i ++) {
13
+ if (binary .charAt (i ) == '0' ) {
14
+ complement .append ('1' );
15
+ } else {
16
+ complement .append ('0' );
17
+ }
18
+ }
19
+ return complement .toString ();
20
+ }
21
+
22
+ public static void main (String [] args ) {
23
+ Scanner scanner = new Scanner (System .in );
24
+
25
+ // Input a binary number
26
+ System .out .print ("Enter a number: " );
27
+ int number = scanner .nextInt ();
28
+
29
+ String binary = Integer .toBinaryString (number );
30
+
31
+ // Compute and print the 1's complement
32
+ String result = onesComplement (binary );
33
+ int n = Integer .parseInt (result , 2 );
34
+ System .out .println ("1's complement of " + number +"(" +binary +")" +" is: " + n + "(" +result +")" );
35
+
36
+ scanner .close ();
37
+ }
38
+ }
39
+
You can’t perform that action at this time.
0 commit comments