181. 将整数A转换为B
如果要将整数A转换为B,需要改变多少个bit位?
注意事项
Both n and m are 32-bit integers.
样例
如把31转换为14,需要改变2个bit位。
(31)10=(11111)2
(14)10=(01110)2
class Solution {
public:
/*
* @param a: An integer
* @param b: An integer
* @return: An integer
*/
int bitSwapRequired(int a, int b) {
// write your code here
int count = 0;
count = getNum(a ^ b);
return count;
}
int getNum(int n) {
if (n == 0) return 0;
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
};