461. Hamming Distance
題目原文
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.解題思路
程式解答
Last updated
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.Last updated
class Solution
{
public:
int hammingDistance(int x, int y)
{
int counter = 0;
int x_xor_y = x ^ y;
for (int i = 0; i < 32; i++)
{
if (x_xor_y % 2)
counter++;
x_xor_y >>= 1;
}
return counter;
}
};