Start learning free

LESSON 307 OF 314 · BIT MANIPULATION

Reverse Bits in C++: O(1) with uint32_t Shifts

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

    C++ · BIT MANIPULATION

    Reverse Bits in C++, explained

    Problem overview

    The method reverseBits takes a uint32_t n, viewed as exactly 32 bits with leading zeros, and returns the number formed by those bits in reverse order: the last bit becomes the first, and so on.

    For n = 1, the 32 bits are 31 zeros and a final 1. Reversed, the 1 comes first, and the number is 2147483648, which is 2 to the power 31. For n = 43261596 the answer is 964176192, and for n = 4294967293 it is 3221225471.

    The statement asks for O(1) time, one step per each of the 32 bits, and O(1) space.

    Approach: take bits from the right, push them in from the right

    Read the bits of n from its right end, one at a time: n & 1 is the last bit, and n >>= 1 drops it so the next bit becomes the last. Build the answer in result: each round, shift result one place left, which opens a 0 at its right end, and copy the bit just taken into that place with OR.

    The first bit taken enters first, then moves left every round that follows, so after 32 rounds it has moved 31 places, to the front. The last bit taken stays at the right end. That is the reversal.

    The loop must always run 32 times, even after n has become 0. Those later rounds push zeros, which shift the earlier bits into their final places. For n = 13, which is 1101, the lesson's code gives these values of result after the first rounds:

    round 1 result=1 n=6
    round 2 result=2 n=3
    round 3 result=5 n=1
    round 4 result=11 n=0
    round 5 result=22 n=0
    round 32 result=2952790016 n=0
    

    After four rounds result is 1011, the reversal of 1101. The 28 remaining rounds append zeros, giving 2952790016, which is 1011 followed by 28 zeros.

    Step by step

    1. Create result as a uint32_t set to 0.
    2. Loop 32 times with i from 0 to 31. Every bit must move, leading zeros included.
    3. Shift and insert: result = (result << 1) | (n & 1). The shift makes room; n & 1 is the bit to place; OR copies it in.
    4. Shift n right with n >>= 1, so its next bit becomes the last one.
    5. Return result.

    The solution in C++

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

    C++ details worth knowing:

    • Why uint32_t. It is an unsigned integer of exactly 32 bits, holding 0 to 4,294,967,295. An int stops at 2,147,483,647, so inputs like 4294967293 and answers like 2147483648 don't fit.
    • Unsigned shifts are safe. Shifting a uint32_t left drops the bits that fall off the left end, with no undefined behaviour. Overflowing a signed int would be undefined behaviour.
    • Right shift fills with zeros. On an unsigned value, n >>= 1 brings in a 0 on the left. On a negative signed int it would typically copy the sign bit instead, and the later rounds would not push zeros.

    Complexity

    Time: O(1). The loop always runs 32 times, whatever the value of n.

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

    Edge cases and common mistakes

    • Stopping when n is 0. That drops the trailing zeros of the answer. With n = 13, stopping after round 4 would return 11 instead of 2952790016.
    • Zero and all ones. 0 reverses to 0, and 4294967295 reverses to itself.
    • Powers of two. n = 2 has its 1 in the second place from the right. It ends second from the left, giving 1073741824.
    • Using a signed type. An int can't hold answers above 2147483647, such as 2147483648 for n = 1.

    Testing

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