A friend of mine was asked this question in an interview. I wasn't able to figure out a solution to this. Question -
Write a function to calculate the number of bit swaps required to convert one integer to other.
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With