Write a function to determine the number of bits required to convert integer A to integer B.

Input: 31, 14

Output: 2

**My initial thoughts:**

31 = 11111

14 = 01110

Take 31 – 14 and we get:

17 = 10001

So we take the difference of A-B or B-A, and check how many 1s in that integer.

**My initial codes:**

public static int numberOfBitsRequiredToConvert(int A, int B) {
int diff = A - B >= 0 ? A - B : B - A;
int count = 0;
for (int i = 0; i < 32; ++i)
count += (diff & (1 << i)) > 0 ? 1 : 0;
return count;
}

**Solutions:**

public static int bitSwapRequired(int a, int b) {
int count = 0;
for (int c = a ^ b; c != 0; c = c >> 1) {
count += c & 1;
}
return count;
}

We can conclude two basic idea from this solution:

- When trying to detect which bits of two numbers are different, we use XOR(^).
- To check each bit of a number, we can keep & it with 1 and then shift to right.

### Like this:

Like Loading...

*Related*