题目链接: leetcode.cn/problems/ha…
题目描述
解题思路
- 首先我们要计算两个数字之间有多少位二进制是不同的。我们就要对两个位进行异或运算
- 异或运算结果放入get1Cnt函数里面去。
- 然后通过这个函数计算我们传递进来的数字里面有多少个1
- 返回结果
代码实现
class Solution {
int get1Cnt(int x){
int cnt=0;
while(x>0){
x &=(x-1);
cnt++;
}
return cnt;
}
public:
int hammingDistance(int x, int y) {
return get1Cnt(x^y);
}
};