Only need 5 lines, Java solution (2ms)


  • 0

    The basic idea is to check 32 times, the rightmost bit in n, if it's equal to 1, add that bit to res.

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

Log in to reply
 

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