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标签
比特位操作 Cracking The Coding Interview
思路
逐位判断即可
code
class Solution {
public:
/**
*@param a, b: Two integer
*return: An integer
*/
int bitSwapRequired(int a, int b) {
// write your code here
int diff = 0, pos = 1;
for (int i = 0; i < 32; i++) {
if ((a & pos) != (b & pos)) {
diff++;
}
pos = pos << 1;
}
return diff;
}
};