Start learning free

LESSON 307 OF 321 · BIT MANIPULATION

Reverse Bits in Java: O(1) Time with a 32-Step Loop

Practice O(1) Read the full explanation

You are given a number n, written in binary with exactly 32 bits (leading zeros included).

Reverse the order of those 32 bits: the last bit becomes the first, the second to last becomes the second, and so on. Return the number that the reversed bits form.

 

Example 1:

Input: n = 43261596
Output: 964176192
Explanation: 43261596 in 32 bits is 00000010100101000001111010011100.
Reversed, the bits are 00111001011110000010100101000000, which is 964176192.

Example 2:

Input: n = 1
Output: 2147483648
Explanation: 1 is 00000000000000000000000000000001.
Reversed, its only 1 bit moves to the front: 10000000000000000000000000000000, which is 231 = 2147483648.

Example 3:

Input: n = 4294967293
Output: 3221225471
Explanation: 4294967293 is 11111111111111111111111111111101.
Reversed, the bits are 10111111111111111111111111111111, which is 3221225471.

 

Constraints:

  • 0 <= n <= 232 - 1
  • The answer is also between 0 and 232 - 1.
  • Numbers this large don't fit in a 32-bit signed integer, so n and the answer use a type that holds 232 - 1: the one in the starter code.
Note:

Your algorithm should run in O(1) time, one step for each of the 32 bits, and use O(1) extra space.



Take the bits of n one at a time from its right end: n AND 1 is the last bit, and shifting n one place right drops it, so the next bit becomes the last one. Where should each bit you take go in the answer?

Build the answer in result, starting from 0. In each round, shift result one place left, which leaves a 0 at its right end, and put the bit you took there with OR. Do it exactly 32 times, even after n has become 0: the first bit you took then ends up in the first of the 32 places.

The loop always runs 32 times, whatever n is: O(1) time.
We keep two numbers, so the extra space is O(1).
STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · BIT MANIPULATION

    Reverse Bits in Java, explained

    Problem overview

    The method reverseBits(long n) receives a number written in binary with exactly 32 bits, leading zeros included. It reverses the order of those 32 bits, so the last bit becomes the first, the second to last becomes the second, and so on, and returns the number the reversed bits form.

    For n = 43261596 the 32-bit form is 00000010100101000001111010011100. Reversed, it is 00111001011110000010100101000000, which is 964176192. For n = 1 the only 1 bit moves from the end to the front, and the answer is 2^31 = 2147483648.

    The input can be as large as 2^32 - 1, and so can the answer. An int stops at 2^31 - 1, so the lesson uses long for both. The target is O(1) time, one step for each of the 32 bits, and O(1) extra space.

    Approach: take bits off one end, push them onto the other

    The last bit of n is n & 1. Shifting n right by one drops that bit, so the next bit becomes the last. Taking bits this way visits them from right to left.

    The answer is built in result from the other side. In each round result is shifted left by one, which leaves a 0 at its right end, and the bit just taken is put there with OR. Bits taken earlier keep moving left while newer ones arrive behind them. The first bit taken ends up farthest left and the last one ends up on the right, which is exactly the mirror image.

    The loop must run exactly 32 times, even after n has become 0. Leading zeros of n are part of the 32 bits, and they become the last bits of the answer. Stopping early would leave the other bits too far to the right.

    For n = 6 the first rounds look like this:

    i=0 result=0 n=3
    i=1 result=1 n=1
    i=2 result=11 n=0
    i=3 result=110 n=0
    

    After all 32 rounds the result is 1610612736, which is 110 followed by 29 zeros: the bits 110 of 6 now sit at the front.

    Step by step

    1. Create result as a long starting at 0. It collects the bits one at a time.
    2. Write a loop that runs 32 times: int i from 0 while i < 32. Every bit moves, leading zeros included.
    3. Shift and insert. Shift result one place left with << 1 and put n & 1 into the free place with |. This line does the reversing.
    4. Drop the bit just used: n >>= 1. The next bit of n becomes the last one.
    5. Return result. After 32 rounds the bit taken first has moved 31 places left, so every bit sits in its mirrored place.

    The solution in Java

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

    The Java details worth a closer look:

    • Why long. The values go up to 4294967295, which an int can't hold: adding 1 to Integer.MAX_VALUE wraps to -2147483648. A long has 64 bits, so 2^32 - 1 fits easily, and the answer for n = 1, 2147483648, prints as a positive number.
    • >>= is safe here. Java's >> copies the sign bit into the freed place, but n is never negative as a long, since it is at most 2^32 - 1. Zeros come in from the left.
    • Precedence. | has lower precedence than << and &, so the parentheses aren't required. They make the three steps easy to read.
    • Assigning to a parameter. n >>= 1 changes only the method's copy of n.

    Complexity

    Time: O(1). The loop runs exactly 32 times, whatever n is.

    Space: O(1). Two numbers are kept, result and n, plus the loop counter.

    Edge cases and common mistakes

    • Zero. All 32 bits are 0, so the answer is 0.
    • All bits set. 4294967295 is 32 ones and reversing it changes nothing, so the answer is 4294967295.
    • Stopping when n becomes 0. A while (n != 0) loop would end after the first round for n = 1 and return 1 instead of 2147483648, because the single bit would never be moved to the front.
    • Using an int result. The bit pattern would be right, but a value such as 2147483648 would come out as -2147483648. The lesson's tests compare numbers, so the result has to be a long.
    • Shifting result after the OR. The order matters: shift first, then insert the bit. Doing it the other way round moves the bit one place too far.
    • Forgetting to shift n. Without n >>= 1 the same bit is taken 32 times.

    Testing

    • n = 43261596 gives 964176192.
    • n = 1 gives 2147483648.
    • n = 4294967293 gives 3221225471.
    • n = 0 gives 0.
    • n = 4294967295 gives 4294967295.
    • n = 2147483648 gives 1.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free