Write a function to determine the number of bits required to convert integer X to integer Y.
Input: 31, 14
Output: 2
This problem seems to be quite complex, however is actually rather simple. Think about finding out which bits in two numbers are different. Simple: with an XOR.
Each 1 in the XOR will represent one different bit between X and Y. Then we can simply count the number of bits that are 1.
public static int swapRequired(int x, int y)
{
int counter = 0;
for (int z = x ^ y; z!= 0; z= z>>1) {
counter += c & 1;
}
return counter;
}