题目描述:
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 z=x^y;
int count=0;
while(z>0)
{
if(z%2==1) count++;
z/=2;
}
return count;
}
};
本文介绍了一种计算两个整数间汉明距离的方法。通过异或运算确定不同位的数量,适用于0到2^31-1之间的整数。举例说明了1与4之间的汉明距离为2。
1909

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



