C++ naive and optimized


  • 0
    X
    class Solution {
    public:
        // naive solution
        /*
        uint32_t reverseBits(uint32_t n) {
            uint32_t ans = 0;
            for(int i = 0, j = 31; i <= 31; ++i, --j){
                uint32_t tmp = n & (1 << i);
                if(tmp){
                    ans |= (1 << j);
                }
            }
            return ans;
        }
        */
        //look up a 4 bit chuck and find out what the reverse is
        char tb[16] = {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15};
        uint32_t reverseBits(uint32_t n) {
            uint32_t cur = 0;
            uint32_t ans = 0;
            uint32_t msk = 0xf;
            for(int i = 0;i < 8; ++i){
                ans <<= 4;
                cur = n & msk;
                cur = tb[cur];
                ans = ans | cur;
                n >>= 4;
            }
            return ans;
        }
    };

Log in to reply
 

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