Interview question: Number of bit swaps required to convert one integer to another
The bit operation which can be used to figure out which bits are different is xor. Each 1
in the xor value will tell the different bit between the two integers.
int getBitSwapCount(int x, int y) {
int count = 0;
for(int z = x^y; z!=0; z = z>> 1) {
count += z & 1;
}
return count;
}
Interview questions aren't only about solutions, they're also (and this is generally even more important that finding a solution) giving you the opportunity to show how you would tackle a novel problem such as this. How would you start on this ? Is there any further information you'd like to know to help you solve it ? Are there any standard functions (in any commonly-used programming language) you'd like to use ?
Give us your best shot, we'll play the interviewer(s) and prompt as you go ...
XOR the values and then count the number of ones in the result