Easy to understand C++ solution in 4ms


  • 0
    P
    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            if(!n) return n;
            
            uint32_t new_n;
            for(int i = 0; i < 32; i++) {
                new_n = (new_n << 1) ^ (n & 1);
                n >>= 1;
                if(!n) {
                    new_n <<= 32 - (i + 1);
                    break;
                }
            }
            return new_n;
        }
    };

Log in to reply
 

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