常见位运算总结
1 ~> 刷前必刷题单
干掉一个数(n)二进制表示中最右侧的 1:
class Solution {
public:
int hammingWeight(int n) {
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
};
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n + 1, 0);
for (int i = 1; i < n + 1; i++) {
ans[i] = ans[i >> 1] + (i & 1);
}
return ans;
}
};










