[力扣] 算法 190 (C++)

190. 颠倒二进制位

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        auto ret = (n >> 16) | (n << 16);// ((ret &amp; 0xffff0000) >> 16) | ((ret &amp; 0x0000ffff) << 16)
        ret = ((ret &amp; 0xff00ff00) >> 8) | ((ret &amp; 0x00ff00ff) << 8);
        ret = ((ret &amp; 0xf0f0f0f0) >> 4) | ((ret &amp; 0x0f0f0f0f) << 4);// 1111 0000
        ret = ((ret &amp; 0xcccccccc) >> 2) | ((ret &amp; 0x33333333) << 2);// 1100 0011
        ret = ((ret &amp; 0xaaaaaaaa) >> 1) | ((ret &amp; 0x55555555) << 1);// 1010 0101
        return ret;
    }
};

发表评论