Wednesday, December 28, 2011

bit swaps required to convert integer A to integer B

Question: How would you find the number of bit swaps required to convert integer A to integer B?

Answer: Gut instinct might suggest that you go through every bit of A and every bit of B while simultaneously updating a count of the bits that are different. But how about a cooler way to solve this?

A key to solving a lot of bit manipulation questions is the use of the XOR functionality.

int bit_swaps_required( int a, int b ) {
unsigned int count = 0;
for( int c = a ^ b; c != 0; c = c >> 1 ) {
count += c & 1;
}
return count;
}
Simple right?

Help share this post through Twitter!

No comments:

Post a Comment