Inplace, no new variable, 4ms c++


  • 0
    S
    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            for(int i=0; i<16; i++)
            {
                uint32_t mask1 = 1<<i;
                uint32_t mask2 = 1<<31-i;
                
                uint32_t i1 = mask1 & n;
                uint32_t i2 = mask2 & n;
                
                i2 >>= 31-2*i; 
                if(i1 == i2) continue;
                
                i1 <<= 31-2*i; 
                if(i1)
                    n += i1;
                else 
                    n -= mask2;
                    
                if(i2)
                    n += i2;
                else 
                    n -= mask1;
            }
            return n;
        }
    };

Log in to reply
 

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