两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x
和 y
,计算它们之间的汉明距离。
注意:
0 ≤ x, y < 2^31
示例:
输入: x = 1, y = 4
输出: 2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
C++实现
class Solution {
public:
int hammingDistance(int x, int y) {
int count = 0;
int result = x ^y;
while (result != 0) {
if (result & 0x01) {
count++;
}
result = result >> 1;
}
return count;
}
};
Java实现
public class Solution {
int hammingDistance(int x, int y) {
int count = 0;
int result = x ^ y;
while (result != 0) {
if ((result & 0x01) > 0) {
count++;
}
result = result >> 1;
}
return count;
}
}
原题地址
https://leetcode-cn.com/problems/hamming-distance/description/