題目來源
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.
解析
兩個整數(shù)的海明距離是指其對應(yīng)二進(jìn)制不同的位數(shù)兴想。如1和4的二進(jìn)制中有兩位不一樣攻走,海明距離是2
解答
- 兩個數(shù)做異或操作
- 將操作結(jié)果轉(zhuǎn)換為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()
測試結(jié)果
![result](https://s27.postimg.org/yeb5bisr7/hamming_distance.png)
result