A log(32) solution using only 25 bit operations and 5 pluses


  • 3
    B

    It is like a binary search, switch every 1 bit, 2 bits, 4 bits, 8 bits, 16 bits at a time.

    const unsigned sh[5] = {0x55555555, 0x33333333, 0x0f0f0f0f, 0x00ff00ff, 0xffffffff};
    uint32_t reverseBits(uint32_t n) {
        for (unsigned i = 0, w = 1; i < 5; ++i, w *= 2)
            n = ((n & sh[i]) << w) + ((n & sh[i] << w) >> w);
        return n;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.