原题链接:Leetcode 461. 汉明距离
代码一:
class Solution {
public:
int hammingDistance(int x, int y) {
int res=0;
while(x || y)
{
res+=(x&1)^(y&1);
x>>=1; y>>=1;
}
return res;
}
};
代码二:
class Solution {
public:
int hammingDistance(int x, int y) {
int res=0;
for(int i=0;i<32;i++)
{
int a=((x>>i)&1);
int b=((y>>i)&1);
if(a^b) res++;
}
return res;
}
};
代码三:
class Solution {
public:
int hammingDistance(int x, int y) {
x=x^y;
int res=0;
while(x)
{
x&=(x-1);
res++;
}
return res;
}
};



