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.
class Solution {
public:
int hammingDistance(int x, int y) {
int result = x ^ y;
int count = 0;
while (result >0) {
if ((result) & 1 == 1)
count++;
result >>= 1;
}
return count;
}
};
本文介绍了一种简单的方法来计算两个整数之间的哈密距离,即二进制位数不同的数量。通过使用亦或运算和位操作,我们提供了一个高效的算法实现。
391

被折叠的 条评论
为什么被折叠?



