AlgoViz

Reverse Bits

Medium

Shift out one side, shift in the other

Problem

Reverse the bits of a 32-bit unsigned integer.

In simple words

Pull bits off the bottom and stack them onto the top of the result, 32 times.

The idea

Pull the lowest bit off the input and push it onto the result, shifting the result left each time, for all 32 positions. The result grows from the top of the input downwards, which is exactly the reversal.

The trick

  • Exactly 32 iterations, even when the number is small — leading zeros matter.
  • Use unsigned types, or the arithmetic right shift drags sign bits in.
  • Divide-and-conquer masks do it in five steps if speed matters.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

1.0100101000001111e+25
0

Step 1 of 2. Here's the example — 00000010100101000001111010011100 Values: 1.0100101000001111e+25.

1/2
Optimal
timeO(32)spaceO(1)
1res=02for i in 0..31:3  res = (res<<1) | (n & 1)4  n >>= 15return res

Input

array
[1.0100101000001111e+25]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
n = 43261596 (32-bit)
Output:
964176192
Explanation:
Flip the 32-bit pattern end to end.

Example 2

Input:
n = 4
Output:
536870912
Explanation:
Bit at position 2 moves to position 29.

Example 3

Input:
n = 1
Output:
2147483648
Explanation:
The lone 1 jumps to the top bit.

Finished the walkthrough? Add it to your streak.