题目来源
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:
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
解答
- 两个数做异或操作
- 将操作结果转换为str
- 遍历str,如果有
'1'
,则距离加1
测试代码
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()