题目描述:链接
解题思路:
- 两个数的异或,如果二进制结果中某一位为1,说明原始数字的对应位置两个数是不同的,因此只需计算两个数异或之后1的个数即可;
- 一个二进制数中1的个数,可以使用n&(n-1)的方法;
class Solution {
public:
int hammingDistance(int x, int y)
{
//两个数异或,为1表示原来的两个数对应的二进制位不同,只需统计异或结果中1的个数
int z = x^y;
int count = 0;
while(z)
{
count++;
// z & (z - 1)每一次可以记一个1
z = z & (z - 1);
}
return count;
}
};