https://leetcode-cn.com/problems/hamming-distance/
#define LL long long
class Solution {
public:
int hammingDistance(int x, int y) {
LL t = x^y;
LL ans=0;
while(t){
ans+=1;
t = t&(t-1);
}
return ans;
}
};
补一张真值表
另外学到了一个 x & (x-1)的妙用
x-1会使得x的最右边的1变为0
x & (x-1) 假如x只有一个1,那么结果就是0了
class Solution {
public:
int hammingDistance(int x, int y) {
x = x ^ y; //异或,只留下两者不同的位数为1
y = 0;
while(x){
y++;
x = x & (x-1);
}
return y;
}
};
python的实现一样的
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
x=x^y
ans=0
while(x):
ans+=1
x=x&(x-1)
return ans
但是更快的是直接调库
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
z=x^y
return bin(z).count("1")
bin的文档解释:
bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an index() method that returns an integer.
来源:CSDN
作者:hhmy77
链接:https://blog.csdn.net/hhmy77/article/details/104698256