题目描述

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 < 2^(31).

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.``````

解法一

思路

``01101 ^ 01011 = 00110``

``````num = 0b00110
count = 0
while num:
num &= num - 1
count += 1
print(count)``````

``````00110 & 00101 = 00100
00100 & 00011 = 00000``````

Python

``````class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
count = 0
xor = x ^ y
while xor != 0:
xor &= (xor - 1)
count += 1
return count``````

Java

``````public class Solution {
public int hammingDistance(int x, int y) {
int count = 0;
int xor = x ^ y;
while (xor != 0) {
xor &= (xor - 1);
count++;
}
return count;
}
}``````

C++

``````class Solution {
public:
int hammingDistance(int x, int y) {
int count = 0;
int xorValue = x ^ y;
while (xorValue != 0) {
xorValue &= (xorValue - 1);
count++;
}
return count;
}
};``````