Amazon Interview Question
Software Engineer / Developerssaw 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;
}
hi! , Everyone loves a persons writing quite definitely! promote many of us keep up a correspondence more info on your own document for Yahoo? I need a pro for this dwelling to unravel this dilemma. Could be that is definitely a person! Looking forward to search an individual. dgdbfbedakaddbba
zhaoyangster that looks correct.
- Developer May 24, 2011I 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;
}
}}