C++ Solution with Loop and Precomputed Table


  • 0
    M

    Using loop:

    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            uint32_t result = 0;
            for (int i = 0; i < 32; ++i) {
                result <<= 1;
                result |= n & 1;
                n >>= 1;
            }
            return result;
        }
    };
    

    Using precomputed table:

    class Solution {
    public:
        Solution() : table_(256) {
            for (uint32_t i = 0; i < 256; ++i) {
                uint8_t n = i, result = 0;
                for (int i = 0; i < 8; ++i) {
                    result <<= 1;
                    result |= n & 1;
                    n >>= 1;
                }
                table_[i] = result;
            }
        }
        
        uint32_t reverseBits(uint32_t n) {
            return
                uint32_t(table_[(n >>  0) & 0xFF]) << 24 |
                uint32_t(table_[(n >>  8) & 0xFF]) << 16 |
                uint32_t(table_[(n >> 16) & 0xFF]) <<  8 |
                uint32_t(table_[(n >> 24) & 0xFF]) <<  0 ;
        }
    private:
        vector<uint8_t> table_;
    };
    

Log in to reply
 

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