Simple 2ms, 5 lines, Java solution (no magic)


  • 1
    O

    Here's version 1, short solution, comments inline:

        public int reverseBits(int n) {
            
            // Let's keep a variable to store 
            // the comparison of bits "i" and "31-i".
            int tmp = 0;
            
            // Iterate over half of the bits of an integer
            // as we'll be processing current bit with its mirror
            for(int i = 0; i < 16; i++){
                
                // Shift the bits by i, so that 
                // bit i becomes bit 0:
                //      n >> i
                // Get value of bit i:
                //      A = (n >> i) & 1
                // Get value of bit 31 - i: 
                //      B = ((n >> (31 - i)) & 1) )
                // Evaluate the difference of bit i vs bit 31-i
                //      tmp = A ^ B
                tmp = ((n >> i) & 1) ^ ((n >> (31 - i)) & 1);
                
                // If difference exists...
                if (tmp > 0){
                    // flip bit i
                    n ^= tmp << i;
                    // flip bit 31-i
                    n ^= tmp << (31-i);
                }
            }
            return n;
        }
    

    Now, let's compact the tmp... Here's shorter 5 line 2ms solution:

        public int reverseBits(int n) {
            for(int i = 0; i < 16; i++){
                if ((((n >> i) & 1) ^ ((n >> (31 - i)) & 1) ) > 0){
                    n ^= 1 << i;
                    n ^= 1 << (31-i);
                }
            }
            return n;
        }
    

Log in to reply
 

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