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的个数。
如十进制除以10,求二进制数各个位上1的个数,可以将其一直除以2,将其余数个数相加。
1版:
class Solution { public: int hammingDistance(int x, int y) { int temp; int i = 0;//计数 temp = x^y; while (temp / 2 != 0) { if (temp % 2 == 1) i++; temp = temp / 2; } if (temp == 1) i++; return i; } };
2.看到 x&(x-1) 可以消去x最右位的1
2版
class Solution { public: int hammingDistance(int x, int y) { int i = 0; int temp = x^y; while (temp) { temp &= (temp - 1); i++; } return i; } };
3版 简化1
class Solution { public: int hammingDistance(int x, int y) { if ((x^y) == 0) return 0; return (x^y) % 2 + hammingDistance(x / 2, y / 2); } };