Bootstrap

LeetCode461汉明距离

参考:https://www.cnblogs.com/shanelau/p/7105141.html

          https://blog.csdn.net/booirror/article/details/53836504

          https://www.cnblogs.com/Amenity-arithmetic/p/8572338.html

解法一:汉明距离为    两个数的二进制按位运算后1的个数,用z=x&y;  while(z!=0){ z=z&(z-1)}(z&z-1相当于每一次循环都将最右边1清除 例 7(0111)和6(0110)相&为6(0110)

解法二:汉明距离为    将两个数和分别和(0001,0010,0100,1000,10000……) 相&,比较不相等则加1(例:1(0001)和0001相&为0001,4(0100)和0001相&为(0000)不相等,所以在最低位他们是不相等,再以此比较0010和0100……

解法三:汉明距离为  两个数二进制按位运算后,调用Integer.bigCount()查1的个数;

参考代码:

解法一:

int Dis = 0;
        int z = x ^ y;
        while (z != 0) {
            Dis++;
            z = z & (z - 1);
        }
        return Dis;

解法二:

int num = 0;
for (int i = 0; i < 32; i++)
{
int val = 1 << i;
if (val > x && val > y) {
break;
}
  if ((x & val) != (y & val)) {
num++;
}
}

return num;

解法三:

return Integer.bitCount(x ^ y);

;