190.颠倒二进制位
题目链接
贴一个纯位运算的版本和一个纯bitset的版本
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
bitset<32>a(n);
string tmp = a.to_string();
reverse(tmp.begin(), tmp.end());
a = bitset<32>(tmp);
return a.to_ulong();
}
};
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ans = 0;
for(int i = 0 ;i < 32 ;i++){
ans |= (n>>i&1)<<(31^i);
}
return ans;
}
};
191.位1的个数
题目链接
偷懒使我快乐
class Solution {
public:
int hammingWeight(uint32_t n) {
bitset<32>a(n);
return a.count();
}
};