Reverse Bits

25 min · reverseBits()

Picture a row of 32 switches. Turn the panel around, and the switch at the far right now belongs at the far left.

Treat n as an unsigned 32-bit integer — a 32-position binary value with no sign. Reverse those 32 bit positions and return the resulting integer.

The fixed width matters:

  • Leading zeroes are part of the 32-position input and move to the right.
  • The input stays below 2^31, so it crosses the judge as a signed-safe integer.
  • The reversed result may set bit 31 and exceed 2^31 - 1; return that non-negative value as a long.

Constraints

  • 0 <= n < 2^31
  • The output is in [0, 2^32 - 1].

Hints

Make the width visible

Write n as exactly 32 binary digits, padding the left side with zeroes. Reversing that string is a clear first solution.

Move one edge at a time

n & 1 extracts the rightmost input bit. Shift the result left before placing that bit into its new position.

Stay non-negative

Run exactly 32 rounds. In languages with signed bitwise operators, don't keep the growing answer in a signed left-shifted value; force inputs to unsigned 32-bit form or use arithmetic doubling so bit 31 remains a non-negative result.

Follow-up

Reversing all 32 positions twice should recover the original number. Can you explain why that remains true when the first reversal produces a value above 2^31 - 1?

Visible cases

Examples

Example 1

ready
Input
n = 43261596
Expected
964176192
Why
reversing all 32 positions produces 964176192

Example 2

ready
Input
n = 1
Expected
2147483648
Why
the lowest bit moves to bit 31

Example 3

ready
Input
n = 0
Expected
0
Why
32 zero bits stay zero

Interview signal

Asked at

AmazonApple
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite