Wednesday, December 7, 2011

Problem on Bit Manipulation


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;
 }

2 comments:

  1. I wonder if calculating the Hamming Weight would be faster than looping:

    http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer

    ReplyDelete
  2. @sandropasquali: As it is mentioned in the follow up comments on the same page, it is dependent on many factors like CPU usage patterns and instruction sets. Although hamming weight seems to be a faster technique as from the first glance.

    ReplyDelete