题目
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的位数。
代码
public int hammingDistance(int x, int y) {
int res = 0;
// 异或
int tmp = x ^ y;
// 每次将 tmp 和 tmp - 1 相与
// 如 0101 & 0100 = 0100
// 0100 & 0011 = 0000
// 相当于每次去除了一个1
while (tmp > 0) {
res++;
tmp = tmp & (tmp - 1);
}
return res;
}