The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
, calculate the Hamming distance.
位运算,需要求两个整数之间的位数差异: 因为 a != b 等价与{a&b == 0;a|b == 1},所以对两个数执行(a|b - a&b),问题转换为求这个数中1的个数。使用循环可以直接求出1的个数。
class Solution {
public:
int hammingDistance(int x, int y) {
int z,distance = 0;
z = (x|y)-(x&y);
while(z!=0)
{
if(z&1==1)
++distance;
z=z>>1;
}
return distance;
}
};
可以优化的地方:
求二进制数中1的个数的时候,可进行优化:
1、判断 x&(x - 1);
2、查表对比法,建立个数和数值的映射,然后将原数据拆分再查找;
3、平行算法:
先考虑求两位数的算法,然后延伸至32位,再在新数上面求4位数的和,依次到最后结果;
求两位数和方法:a右移一位再加上a;在延伸至32位时为了排除前面数据的影响,需要&(……0101)