190. Reverse Bits 逆置位序列

190. Reverse Bits 逆置位序列

解法:多次分组逆置

abcdefgh -> efghabcd -> ghefcdab -> hgfedcba

前 16 位后 16 位交换,然后 16 位中的前 8 位和后 8 位交换,依次到个位的交换,即完成整个位序列的逆置

uint32_t reverseBits(uint32_t n) {
    n = (n<<16) | (n>>16);
    n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
    n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
    n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
    n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
    return n;
}

#位运算