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.
思路:汉明距离是指两个数字之间的二进制数不相同的位的个数。上面的例子中是第一位和第三位是不相同的所以其结果是2。所以比较重要的一点就是十进制转换为二进制,然后对两个二进制串进行比较即可。
进制转换:当要求十进制数 x 的 k 进制表示时,我们只需不断的重复对 x求余(对 k ),求商(除以 k ),即可由低到高依次得到各个数位上的数。反过来,要求得由 k 进制表示的数字的十进制值时,我们需要依次计算各个数位上的数字与该位权重的积(第 n 位则权重为 k^(n − 1)),然后将它们依次累加即可得到该十进制值。
解决代码:(python)
class Solution:
self.arr = []
a=self.distance(self.bits(x),self.bits(y))
return a
def bits(self,x):
self.arr=[]
index=0
while True:
self.arr.append(int(x%2))
x/=2
if int(x)==0:
break
return self.arr
def distance(self,x,y):
result=0
if(len(x)>=len(y)):
b=x
else:
b=y
len1=min(len(x),len(y))
for i in range(len1):
if x[i]!=y[i]:
result+=1
for i in range(len1,len(b)):
if b[i]==1:
result+=1
return result
实在是过于繁琐,最强一行代码解决:
return bin(x^y).count('1')
对x,y进行异或操作:只有在两个比较的位不同时其结果是1,然后统计1的个数即可!吊到飞起!