Number of bits required to convert integer A to B

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:

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: