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.
LeetCode:链接
汉明距离,即两个数的二进制表示中对应位上数字(0/1)不相同的个数。很容易想到这题应该用异或。接下来的问题就转换成数异或的结果中1的个数。
怎么数1的个数?这里有个简单的方法:
num = 0b00110
count = 0
while num:
num &= num - 1
count += 1
print(count)
每次num &= num - 1
,num
二进制值的最低位1都会变成0,即每次去掉一个1,直到其值为0。
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
xor = x ^ y
count = 0
while xor:
xor &= xor - 1
count += 1
return count