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.
Note:
0 ≤ x
, y
< 231.
Example:
Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.
给定两个整数,求其汉明距离。汉明距离指两个数字在二进制上相同位不数值不相同的个数。我们很容易知道异或运算后的值即可表示这两个数在所有位上是否相同的情况,异或值在某一位为1说明两数在该位不相等,为0两数在该位相等。因此,上述问题可转换为求取异或值中位数为1的个数。在剑指offer的第15题中, 有该题的解法,常规解法如下,其原理主要是利用移位操作,按位求与,值不为0说明在该位有值1,int类型共有32位,循环32次即可统计出不为1的位数:
int hammingDistance(int x, int y) {
int xor_sum = x ^ y;
int ret = 0;
unsigned int flag_idx = 0x01;
for(int i = 0; i < 32; i++)
{
if((xor_sum & flag_idx) != 0)
ret++;
flag_idx <<= 1;
}
return ret;
}
书中还提到另外一种巧解,该方法利用了以下规律:将一个整数减去1,再和原整数做与运算,会将该整数最右边的1变成0。因此,求有1的位数就变成了上述多少次的操作。代码如下:
int hammingDistance(int x, int y) {
int xor_sum = x ^ y;
int ret = 0;
while(xor_sum)
{
ret++;
xor_sum = (xor_sum - 1) & xor_sum;
}
return ret;
}