常见位运算总结
在算法面试中,位运算往往能带来 O(1) 的空间优化或更高效的逻辑表达。掌握几个核心技巧,如利用 n & (n-1) 消除最右侧的 1,以及异或运算的自反性,可以解决许多看似复杂的问题。
基础技巧回顾
消除最右侧的 1
class Solution {
public:
int hammingWeight(int n) {
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
};
汉明距离计算
class Solution {
public:
int hammingDistance(int x, int y) {
int val = x ^ y;
int count = 0;
while (val) {
val &= (val - 1);
count++;
}
return count;
}
};
异或消去法
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
};


