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 < 2^31.
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.
汉明距离是以理查德·卫斯里·汉明的名字命名的。在信息论中,两个等长字符串之间的汉明距离是两个字符串对应位置的不同字符的个数。换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。
思路
- 首先要想到异或,对x和y取异或后,结果中所有不同位为1;
- 计算1和1间的最大距离,利用xor ^(xor-1)抵消掉最右侧的1,迭代之,直到xor变为0.
Code
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
#xor is used to identify the different bits
xor = x ^ y; # so different bits would become 1
n=0;
#next, calculate biggest distance
while xor>0:
n+=1
xor = xor & (xor-1) # xor & (xor-1): set rightest 1 to 0
return n;