LeetCode461 Hamming Distance

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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.

0 ≤ x, y < 2^31.

样例

1
2
3
4
5
6
7
8
9
10
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.

思路

给两个32-bit数,求它们有多少个不同的二进制位。
判断数x的第i为是否为1:(x >> i) & 1
异或运算性质:0 ^ 0 = 1 ^ 1 = 0 1 ^ 0 = 0 ^ 1 = 1

代码

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int hammingDistance(int x, int y) {
int ans = 0;
for (int i = 0; i < 32; ++i) {
if (((x >> i) & 1) ^ ((y >> i) & 1)) ans++;
}
return ans;
}
};
分享到 评论