Problem
Write a function to determine the number of bits required to convert integer A to integer B.
Input: 31, 14
Output: 2
Solution
#include <iostream>
using namespace std;
int bits_different(int a, int b)
{
int dif = a^b;
int bits = 0;
while(dif != 0){
bits ++;
dif &= (dif - 1);
}
return bits;
}
int main(int argc, char* argv[])
{
cout.unsetf(ios::dec);
cout.setf(ios::hex);
cout.setf(ios::showbase);
int a = 31;
int b = 14;
cout << "different bits is: "<< bits_different(a, b) << endl;
return 0;
}