Hamming Distance(汉明距离)

Introduction

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.

解法一:

两个数字之间的汉明距离就是其二进制数对应位不同的个数。按位分别取出两个数对应位上的数并异或,满足条件则累加

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0;
for (int i = 0; i < 32; ++i) {
if ((x & (1 << i)) ^ (y & (1 << i))) {
++res;
}
}
return res;
}
};

解法二:

直接将两个数字异或起来,遍历异或结果的每一位并统计个数

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0, exc = x ^ y;
for (int i = 0; i < 32; ++i) {
res += (exc >> i) & 1;
}
return res;
}
};

解法三:

最高效的解法

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0, exc = x ^ y;
while (exc) {
++res;
exc &= (exc - 1);
}
return res;
}
};

解法四:

递归终止的条件是当两个数异或为0时,表明此时两个数完全相同,我们返回0,否则我们返回异或和对2取余加上对x/2和y/2调用递归的结果。异或和对2取余相当于检查最低位是否相同,而对x/2和y/2调用递归相当于将x和y分别向右移动一位,这样每一位都可以比较到。

1
2
3
4
5
6
7
class Solution {
public:
int hammingDistance(int x, int y) {
if ((x ^ y) == 0) return 0;
return (x ^ y) % 2 + hammingDistance(x / 2, y / 2);
}
};

参考资料