Optimized C++ solution (7 ms) with space for improvement


  • 2
    L

    There space for improvement, just declaring table for 256 values will reduce operations by quarter.

    class Solution {
        private:
            char table[16] = {0, 0b1000, 0b100, 0b1100, 0b10, 0b1010, 0b0110, 0b1110, 1, 9, 0b101, 0b1101, 0b11, 0b1011, 0b111, 15};
        public:
            uint32_t reverseBits(uint32_t n) {
                uint32_t ret = 0;
                int shift = 28;
                while (n) {
                    ret |= table[n&0x0F]<<shift;
                    n = n >> 4;
                    shift -= 4;
                }
                return ret;
            }
        };

Log in to reply
 

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