Leetcode 461: Hamming Distance

题目来源

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

Example:

1
2
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和4的二进制中有两位不一样,海明距离是2

解答

  1. 两个数做异或操作
  2. 将操作结果转换为str
  3. 遍历str,如果有'1',则距离加1

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def main():
def hammingDistance(x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
res = 0
for c in str(bin(x ^ y)):
if c == '1':
res += 1

return res

print hammingDistance(1, 4)

if __name__ == '__main__':
main()

测试结果(领先100%)

result

0%