Take an XOR of two numbers (say a and b) and count the number of units in ^ b
int bitsSwapRequired (int a, int b){ int count = 0; for (int c = a ^ b; c!=0 ; c >> 1) count += c & 1; return count; }
We can do this a little better than just flipping c repeatedly, checking the least significant bit, we can continuously flip the right-most bit set to 1 and calculate how long it takes c to reach 0. Operation c = c and (c- 1) will clear the rightmost bit set to 1 in c.
int bitsSwapRequired (int a, int b){ int count = 0; for (int c = a ^ b; c != 0; c = c & (c-1)) count ++; return count; }
Deepak sharma
source share