Sweaty Imposter

Reverse Bits

EasyBitwise XORBlind 75JuniorOpen on LeetCodeUpdated

You're given a 32-bit unsigned integer n. Reverse the order of its 32 bits, so bit 0 becomes bit 31 and bit 31 becomes bit 0, and return the result as an unsigned integer. In Java, which has no unsigned int, the input and output are signed ints holding the same 32-bit patterns.

Examples

n = 1 returns 2147483648

Only bit 0 is set, so the result has only bit 31 set, which is 2^31. In Java this pattern prints as -2147483648.

n = 6 returns 1610612736

6 has bits 1 and 2 set. They move to bits 30 and 29, and 2^30 + 2^29 = 1610612736.

n = 0 returns 0

No bits are set, so there is nothing to move.

Constraints

  • n is a 32-bit unsigned integer: 0 <= n <= 2^32 - 1.

Hints

Hint 1

Read n's bits from the lowest up. Where should the first bit you read end up?

Hint 2
A pointer toward the approach
Hint 3
The full approach, step by step

Drill This: Your Approach First

Approach

Build the result one bit at a time. Repeat 32 times: shift result left by one, copy n's lowest bit into it with result | (n & 1), then shift n right by one. The bit read first ends up shifted 31 places, at the top. Always run all 32 rounds, since leading zeros in n become trailing zeros in the result. O(1) time and space.

Time

O(1)

Space

O(1)

Pitfall

Stopping when n reaches 0. That drops the zeros that belong at the bottom of the result, so 1 comes back as 1 instead of 2^31. In Java, also shift n with >>> so the sign bit does not copy itself in.

Solutions

public class Solution {
    public int reverseBits(int n) {
        int result = 0;
        for (int i = 0; i < 32; i++) {
            result = (result << 1) | (n & 1);
            n >>>= 1;
        }
        return result;
    }
}
Drill This