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.
代码实现
public int HammingDistance(int x, int y)
{
///a and y are different bits, so we think the XOR
///think:0001(1D)
/// 0100(4D)
///xor = 0101(1D^4D)
int dist = 0, xor = x ^ y;
while (xor > 0)
{
///xor & (xor-1): it sets the rightest 1 bit to 0 bit of xor.
++dist;
xor = xor & (xor - 1);
}
return dist;
}
题库
leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp