[LeetCode 190,191][简单]颠倒二进制位/位1的个数

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();
    }
};
发布了104 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/IDrandom/article/details/104238606