题目链接:https://leetcode.com/problems/hamming-distance/description/
方法一
题目解析:从%2的情况来计算,换成二进制来计算差异。
代码如下:0ms Accepted
class Solution {
public:
int hammingDistance(int x, int y) {
int dis = 0;
while(x > 0 && y > 0)
{
if(x % 2 != y % 2)
dis++;
x /= 2;
y /= 2;
}
while(x > 0)
{
if(x % 2)
dis++;
x /= 2;
}
while(y > 0)
{
if(y % 2)
dis++;
y /= 2;
}
return dis;
}
};
方法二
题目解析:既然是二进制数位不同的有多少个,可以先做异或操作,然后计算“1”的个数。
代码如下:0ms Accepted
class Solution {
public:
int hammingDistance(int x, int y) {
int result = x ^ y;
int cnt = 0;
while(result)
{
result = result & (result - 1);
cnt++;
}
return cnt;
}
};