Amazon Interview Question Software Engineer / Developers
0of 0 votesGiven two unsigned integers, write an efficient function which returns the no. of bits needs to be flipped of one to generate the other.
saw the solution before: Use XOR
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;
}
zhaoyangster that looks correct.
- Developer on May 24, 2011 Edit | Flag ReplyI have one variation/minor improvement to suggest, use c=c&c-1 instead of c=c>>1 and you only loop once for each bit, instead of all the bit positions.
{{
int bit_swaps_required( int a, int b ) {
unsigned int count = 0;
for( int c = a ^ b; c != 0; c = c & c-1 ) {
++count;
}
return count;
}
}}