LeetCode—Hamming Distance
开始刷LeetCode,自己实现并进行改正,并学习其他更优解。
#461
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,将1累加起来就是两个数字的汉明距离。
- Python
class Solution(object):
def hammingDistance(self, x, y):
return bin(x^y).count("1")
bin函数的作用是将x^y的异或结果二进制数转换为字符串,然后count统计其中1的次数。就能够得到两个数的Hamming Distance。
- Java
class Solution{
public int hammingDistance(int x, int y) {
int xor = x ^ y,count = 0;
for (int i = 0;i < 32;i++)
count += (xor >> i) & 1;
return count;
}
将两位数的异或的二进制结果分别与1进行&,统计结果,并将二进制右移i位。
- C++
看了各位大神,c++有多种答案,记录下方便学习。
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&,结果进行异或,记录1的次数。这样分别操作比较麻烦,将两个二进制数异或,再遍历结果的每一位。
class Solution{
public:
int hammingDistance(int x,int y){
int res = 0,xor = x ^ y;
for(int i = 0;i < 32;i++){
res += (xor >> i) & 1;
}
return res;
}
};
还有一种递归的方法,也很简洁明了。
class Solution{
public:
int hammingDistance(int x,int y){
if ((x ^ y) == 0)
return 0;
return (x ^ y) % 2 + hammingDistance(x / 2, y / 2);
}
};
还看到一种做法,很巧妙很高效,将两个数进行异或,通过num&(num-1)移除位数位1,这样就不需要处理所有位数。代码如下:
class Solution{
public:
int hammingDistance(int x,int y){
int res = 0,xor = x ^ y;
while (xor) {
++res;
xor &= (xor - 1);
}
return res;
}
};
上面的xor只是表示是异或,在实际程序中要换个变量名。