Skip to content

Commit dbfddce

Browse files
authored
Merge pull request ghostmkg#223 from Ansh-Vikalp/Ansh-Vikalp-patch-2
Program to Count Bits to Flip for Number Conversion
2 parents ea52586 + 6940bec commit dbfddce

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Important Questions/BitFlipCount.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.util.*;
2+
3+
public class BitFlipCount {
4+
5+
// Method to count the number of bits to flip to convert 'a' to 'b'
6+
public static int countBitsToFlip(int a, int b) {
7+
// XOR of a and b gives the positions where the bits differ
8+
int xor = a ^ b;
9+
int count = 0; // Initialize a counter to count differing bits
10+
11+
// Loop until all differing bits are cleared
12+
while (xor != 0) {
13+
// This operation clears the rightmost set bit in xor
14+
xor = xor & (xor - 1);
15+
count++; // Increment the count for each set bit
16+
}
17+
18+
return count; // Return the total number of bits to flip
19+
}
20+
21+
public static void main(String[] args) {
22+
Scanner sc = new Scanner(System.in);
23+
int a = sc.nextInt();
24+
int b = sc.nextInt();
25+
26+
// Output the number of bits to flip to convert 'a' to 'b'
27+
System.out.println("Bits to flip: " + countBitsToFlip(a, b));
28+
29+
sc.close();
30+
}
31+
}

0 commit comments

Comments
 (0)