ReZero's Utopia.

reverse the bits

Word count: 136Reading time: 1 min
2019/07/17 Share

Input: 00000010100101000001111010011100

Output: 00111001011110000010100101000000

Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

https://leetcode.com/problems/reverse-bits/discuss/54741/O(1)-bit-operation-C%2B%2B-solution-(8ms)

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
n = (n >> 16) | (n << 16); // swap the suffix 16 bits and prefix 16 bits position
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8); // go head but minimal the size
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
return n;
}
};

Explanation:
// 12345678
// 56781234
// 78563412
// 87654321

CATALOG