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.
思路:
先通过异或得到不同的位,然后计数。
题解:
int hammingDistance(int x, int y) {
int v = x ^ y;
int nbits(0);
while(v) {
if (v & 1) {
++nbits;
}
v >>= 1;
}
return nbits;
}