Java solution. A different idea by swap the first bit and the last bit.


  • 0
    A
    public int reverseBits(int n) {
        for(int i = 0; i < 16; i ++) {
            n = swapBits(n, i, 32 - i - 1);
        }
        return n;
    }
    private int swapBits(int n, int i, int j) {
        int lower = (n >> i) & 1;
        int higher = (n >> j) & 1;
        if((lower ^ higher) != 0) { // if the first bit is not equal to the last bit, swap them.
            return n ^= (1 << i) | (1 << j);
        }
        return n;
    }

Log in to reply
 

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