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.
思路:即二进制化之后对应位上不同的位的数目,所以将两个数相异或之后得到的数,该数二进制化后为1 的位的个数即汉明距离。
知识点:
1.异或操作:x^y
2.统计一个数二进制后为1的位的数目
代码1:
class Solution {
public:
int hammingDistance(int x, int y) {
int z,dis=0;
z=x^y;
while(z)
{
++dis;
z=z & (z-1);
}
return dis;
}
};
代码2:
class Solution {
public:
int hammingDistance(int x, int y) {
int z=x^y;
int res=0;
while(z){
if(z&1){res++;}
z=z>>1;
}
return res;
}
};
代码3:
class Solution {
public:
int hammingDistance(int x, int y) {
bitset<32> xBS(x);
bitset<32> yBS(y);
int count = 0;
for(int i = 0; i < 32; i++)
{
if(xBS[i] != yBS[i])
{
count++;
}
}
return abs(count);
}
};
bitset
用于处理二进制位集。是一种类模板,头文件为
<bitset> ,如何使用作了解。