Example: Count the number of bits to convert A to B - rFronteddu/general_wiki GitHub Wiki
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;