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;
}
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;
}
you haven't defined 'c'
ReplyDelete@Anonymous : thanks for pointing out. I corrected the same. :)
ReplyDelete