leetcode 461 hamming distance

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:

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位的数,对x异或y中的每一位进行累加即可
1
2
3
4
5
6
7
8
9
10
11
12
class (object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
count = 0
for i in range(32):
mask = 1 << i
count += 1 if ((x ^ y) & mask) > 0 else 0
return count
  • 如果没有给定数的范围,可以用最小二乘法来求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class (object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
if x == y:
return 0

xor = x ^ y
count = 0
while xor != 0:
if xor % 2 == 1:
count += 1
xor = xor // 2
return count