Start learning free

LESSON 593 OF 673 · BIT MANIPULATION

Reverse Bits in Python: 32 Rounds of Shift and OR

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

    PYTHON · BIT MANIPULATION

    Reverse Bits in Python, explained

    Problem overview

    The method reverseBits receives a number n 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 = 1, the 32-bit form is 31 zeros followed by a 1. Reversed, the single 1 moves to the front and the result is 2147483648, which is 2 to the power of 31. For n = 43261596 the 32 bits are 00000010100101000001111010011100, and reversed they are 00111001011110000010100101000000, which is 964176192.

    The lesson asks for O(1) time (one step for each of the 32 bits) and O(1) extra space.

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

    Take the bits of n one at a time from its right end. n & 1 is the last bit, and shifting n one place right drops it, so the next bit becomes the last. As you take bits, build the answer from the right: shift result one place left, which leaves a 0 at its right end, and copy the bit you took into that place with OR.

    The first bit taken ends up moved left by every later round, so after 32 rounds it sits at the front. The last bit taken is never moved and stays at the right end. That is exactly the mirror image.

    All 32 rounds must run, even after n has become 0. The leading zeros of n are bits too: they become the last bits of the answer, and the rounds that handle them are what push the earlier bits into their correct places.

    Step by step

    1. Create result, starting at 0. It collects the bits one at a time.
    2. Loop 32 times, with i over range(32). Each round moves one bit.
    3. Shift and copy. Set result = (result << 1) | (n & 1). The shift makes room, n & 1 isolates the last bit of n, and | puts it into the free place. This line does the reversing: bits taken earlier keep moving left while newer ones come in behind them.
    4. Drop the bit you used, with n >>= 1. The next bit of n becomes the last one.
    5. Return result.

    The solution in Python

    class Solution:
        def reverseBits(self, n: int) -> int:
            result = 0
            for i in range(32):
                result = (result << 1) | (n & 1)
                n >>= 1
            return result
    

    Python details worth knowing

    • No sign problems. Python integers have no fixed size, and result is built from non-negative values, so it simply grows to 32 bits. The top bit of the answer doesn't turn it negative, and values such as 2147483648 come out as ordinary positive numbers.
    • The loop variable i is unused. It only counts the rounds. Many Python programmers write _ for such a variable, but the lesson's name is fine.
    • n >>= 1 shifts n right and assigns the result back to n. It rebinds the local name, so the caller's value isn't changed.
    • Bits above 32 are ignored. Only the lowest 32 bits of n are looked at, which is why the loop count, not the value of n, decides when to stop.

    Running it

    Printing the inputs and results as 32-bit binary strings shows the mirror image clearly:

    n      = 00000010100101000001111010011100  (43261596)
    result = 00111001011110000010100101000000  (964176192)
    
    n      = 00000000000000000000000000000001  (1)
    result = 10000000000000000000000000000000  (2147483648)
    
    n      = 11111111111111111111111111111101  (4294967293)
    result = 10111111111111111111111111111111  (3221225471)
    

    The third pair shows the same thing for a number with a single 0 bit: the 0 sits second from the right in n and second from the left in the result.

    Complexity

    Time: the loop always runs 32 times, whatever n is, so the time is O(1).

    Space: two numbers, result and n, are kept, so the extra space is O(1).

    Edge cases and common mistakes

    • Stopping when n becomes 0. Writing while n: instead of the 32-round loop breaks every number with leading zeros. With n = 1 the loop would run once and return 1, not 2147483648.
    • Zero. All 32 bits are 0, so the result is 0.
    • All bits set. The result is 4294967295, the same number.
    • Shifting in the wrong order. The shift of result must come before the OR. Doing the OR first and shifting afterwards puts every bit one place too far left and leaves the last place empty.
    • Forgetting the parentheses around n & 1. In (result << 1) | (n & 1) they keep the intent clear. The operators have a fixed priority (<<, then &, then |), but explicit parentheses spare the reader from remembering it.

    Testing

    These results come from running the solution:

    nResult
    00
    12147483648
    43261596964176192
    42949672933221225471
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free