版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/82705339
题目:
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
The above arrows point to positions where the corresponding bits are
different.
解释:
可以用暴力对比法,在对比之前先把两个数字的二进制数的长度变成一致的(前面补0,在python中可以用str.zfill(len)函数),事实上,求汉明距离就是求两个数字异或后的结果中1的个数~用异或可以简化求解
python代码(zfill法):
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
if x==y:
return 0
x=bin(x)[2:]
y=bin(y)[2:]
x=x.zfill(max(len(x),len(y)))
y=y.zfill(max(len(x),len(y)))
count=0
for i in range(len(x)):
if x[i]!=y[i]:
count+=1
return count
python 代码(异或法):
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')
c++代码(异或法),c++中统计异或结果中的1的个数不想python那么方便(因为python的二进制实际上是一个字符串):
class Solution {
public:
int hammingDistance(int x, int y) {
int n =x^y;
int dist=0;
while(n)
{
dist+=1;
n&=n-1;
}
return dist;
}
};
总结:
c++中,求二进制中1的个数
while (n) {
++dist;
n &= n - 1;
}
可以看到n&(n-1)这个操作是将n原来的最右边的1变为0了。
重复操作,有多少个1,这个操作就可以执行多少次。