Wednesday 21 August 2013

Bits required to convert integer A into integer B

Determine the number of bits required to convert integer A into integer B.
Ex:

Input :  integer A = 4, B = 2.
output : 2 bits

Solution:

int bitsRequired(int a, int b){
     int count = 0; //count of required bits
     int xor = a ^ b;
   
     for(int i = xor; i != 0; ){
          count += i & 1;
          i = i >> 1;
     }
     return count;
}

2 comments:

  1. you haven't defined 'c'

    ReplyDelete
  2. @Anonymous : thanks for pointing out. I corrected the same. :)

    ReplyDelete