Leet Code 461:汉明距离
求两个整数二进制位数不同的个数
异或:^ 不同为1,相同为0
快解
int hammingDistance(int x, int y) {
int xorresult=x^y;
int count=0;
while(xorresult!=0)
{
xorresult=xorresult&(xorresult-1);
count++;
}
return count;
}
慢解
int hammingDistance(int x, int y) {
int count=0;
while(x!=0 || y!=0){
if((x&1) ^ (y&1)) count++;
x=x>>1;y=y>>1;
}
return count;
}