1. 题目来源
链接:461. 汉明距离
2. 题目解析
首先问题可以转化为:求 x^y
中二进制表示下 1 的个数。
显然,移位操作可以做,树状数组的 lowbit()
操作也可以,使用 x &=(x-1)
清掉末尾 1 也是可以的。
时间复杂度: O ( l o g n ) O(logn) O(logn)
空间复杂度: O ( 1 ) O(1) O(1)
代码:
// 直接移位
class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0;
for (int i = 0; i <= 31; i ++ ) {
if ((1 << i & x) != (1 << i & y))
res ++ ;
}
return res;
}
};
// x^y
class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0;
x = x ^ y;
for (int i = 0; i <= 31; i ++ ) {
if ((1 << i & x))
res ++ ;
}
return res;
}
};
// lowbit 操作
class Solution {
public:
int lowbit(int x) {
return x & -x;
}
int hammingDistance(int x, int y) {
int res = 0;
x ^= y;
while (x) {
x -= lowbit(x);
res ++ ;
}
return res;
}
};
// 位运算技巧
class Solution {
public:
int hammingDistance(int x, int y) {
int res = 0;
x ^= y;
while (x) {
x &= x - 1;
res ++ ;
}
return res;
}
};