File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments