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表示不同,0表示相同。
然后两个数再分别右移一位,用以比较下一位。直至两个数都为0。
class Solution
{
public:
int hammingDistance(int x, int y)
{
int cnt=0;
while(x||y)
{
if((x&1)xor(y&1))
cnt++;
x=x>>1;
y=y>>1;
}
return cnt;
}
};