Problem
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 < 2^31.
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.
Solution
Hamming Distance的定义:任意两个数字对应的二进制数,如1的二进制表示是0001,4的二进制表示是0100,对于1和4来说,它们的二进制表示中对应的位有两位不同(1的最低位是1,4的最低位是0;1的第三位是0,4的第三位是1),所以它们的Hamming Distance = 2。
既然涉及到位数的异同,自然就想到了异或运算。
- A异或B = (~A)B + A(~B)
- 在C++中,异或运算符是^
例如:z = x ^ y;
求
z = x ^ y
,再求出z中1的数量,这个数量就是要求的Hamming Distance.
Code (C++)
Version 1
class Solution {
public:
int hammingDistance(int x, int y) {
int z = x ^ y; //求x和y的异或
int count = 0;
for (; z; count++){
//逐个清除z最右边的1
//循环的终止条件是z==0
z &= z - 1;
}
return count;
}
};
Note: 对
z &= z - 1
的解释
举两个例子:
1. 6(0110)和7(0111),6 & 7 = 0110,消去了7最右边的1
2. 7(0111)和8(1000),7 & 8 = 0000,消去了8最右边的1
总的来说就是,z - 1是从z的最右边减去1,求 z & (z - 1)可以消去z最右边的1.
在这道题中,消去多少个1,就意味着x和y的Hamming Distance有多大。
Version 2
第二个版本的思路就比较正常,老老实实求z中1的位数。
可以通过从最低位开始逐位和1进行与运算:
1. 结果是1说明z的该位是1,计数器+1,然后将z右移1位
2. 结果是0说明z的该位是零,计数器不变,z右移1位。
class Solution {
public:
int hammingDistance(int x, int y) {
int z = x ^ y;
int count = 0;
for (; z; z >>= 1){
if (z & 1)
count++;
}
return count;
}
};
Summary
- 了解了Hamming Distance的定义。
- 了解了C++中的移位运算(<<和>>)、与运算(&)、异或运算(^)
- 虽然这道题是LeetCode上AC率最高的一道题,但是依然有一定难度,考察了之前很少涉及的位运算。