461. Hamming Distance
- Difficulty: Easy
TheHamming distancebetween two integers is the number of positions at which the corresponding bits are different.
Given two integersxandy, 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就是清零其他位,只保留最后一位。所以每次都比较x&1和y&1,如果不相等就cnt加1,记住每次比较完两个数都要向后移一位。
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
cnt = 0
while x or y:
if x & 1 != y & 1:
cnt += 1
x >>= 1
y >>= 1
return cnt