原题网址:https://www.lintcode.com/problem/flip-bits/description
描述
如果要将整数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
比特位操作
思路:按位异或,统计结果数中有多少个bit位是1,结果中bit位为1说明该数位上两个数的数值不同,需要改变。
AC代码:
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 c=a^b;
int count=0;
for (int i=0;i<32;i++)
{
if((c>>i)&1)
{
count++;
}
}
return count;
}
};