Simple Solution By Appending Bits In Reversed Order

  • 0

    Basically, I get the last bit of N and append it to the result which is the reversed bit order of N. To append, move the current result 1 bit to the left, and OR this result with the new rightmost bit of N.

    public int reverseBits(int n) {
        int mask = 1;
        int result = 0;
        for (int i = 0; i < 32; i++){
            result = result << 1;
            int mostRightBit = n & mask;
            result = result | mostRightBit;
            n = n >> 1;
        return result;

Log in to reply

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