190. Reverse Bits

1. Description

Reverse bits of a given 32 bits unsigned integer.

2. Example

Example 1

Input: n = 43261596
Output: 964176192

Example 2

Input: n = 2147483644
Output: 1073741822

3. Constraints

  • 0 <= n <= 2$^{31}$ - 2
  • n is even.

4. Solutions

Divide and Conquer

Time complexity: O(1)
Space complexity: O(1)

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        const uint32_t M1 = 0x55555555; // 01010101010101010101010101010101
        const uint32_t M2 = 0x33333333; // 00110011001100110011001100110011
        const uint32_t M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
        const uint32_t M8 = 0x00ff00ff; // 00000000111111110000000011111111

        n = (n >> 1) & M1 | (n & M1) << 1;
        n = (n >> 2) & M2 | (n & M2) << 2;
        n = (n >> 4) & M4 | (n & M4) << 4;
        n = (n >> 8) & M8 | (n & M8) << 8;

        return n >> 16 | n << 16;
    }
};
comments powered by Disqus