Skip to content

Example: Count the number of bits to convert A to B

Roberto Fronteddu edited this page Jul 7, 2024 · 1 revision

Given two numbers A and B. Write a program to count the number of bits needed to be flipped to convert A to B.

The number of xor set bits will give us the number of bits to change.

n = a ^ b;
int count = 0;
while (n != 0) {
    count++;
    // remove the rightmost 1 bit from n. 
    // n-1 flips all the bit after the rightmost 1 and itself, the end leaves the remaining 1 set bits
    n &= (n - 1); 
}
return count;
Clone this wiki locally