Friday, December 9, 2011

Write a function to determine the number of bits required to convert integer A to integer B. Input: 31, 14 Output: 2

Each 1 in the xor will represent one different bit between A and B. We then simply need to count the number of bits that are 1.

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

No comments:

Post a Comment