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.
这个题目是要我们算两个正整数异或之后有多少个1。
第一步:z =x^y
第二步:算z二进制数有多少个1
第三步:设置一个计数器,把这个数与1相与然后右移,是1计数器+1,如果不是继续右移。
不多说了,看下面代码
class Solution {
public:
int hammingDistance(int x, int y) {
int z = x^y;
int count = 0;
while(z>0)
{
if(z&1 == 1)
count++;
z=z>>1;
}
return count;
}
};