Example 1
ready- Input
n = 43261596- Expected
964176192- Why
- reversing all 32 positions produces 964176192
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:
2^31, so it crosses the judge as a signed-safe integer.2^31 - 1; return that non-negative
value as a long.0 <= n < 2^31[0, 2^32 - 1].Hints
Write n as exactly 32 binary digits, padding the left side with zeroes. Reversing
that string is a clear first solution.
n & 1 extracts the rightmost input bit. Shift the result left before placing that
bit into its new position.
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.
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
n = 43261596964176192n = 12147483648n = 00Interview signal
Format n as exactly 32 binary digits, reverse those characters, then parse the result
back into an integer. Padding is essential: without it, the zeroes on the left never get
a chance to move to the right.
def reverse_bits(n: int) -> int:
bits = f"{n:032b}"
return int(bits[::-1], 2)Time O(32). Space O(32) for the padded string and its reversal. Since the width never changes, both costs are constant with respect to input size.
You don't need the string. Read the lowest bit of n, make room on the right side of
the answer by shifting the answer left, then place the extracted bit. An unsigned right
shift moves the next input bit into position.
def reverse_bits(n: int) -> int:
reversed_value = 0
for _ in range(32):
reversed_value = (reversed_value << 1) | (n & 1)
n >>= 1
return reversed_valueExactly 32 rounds preserve the leading zeroes as trailing zeroes. Python integers grow
as needed, so a set bit 31 stays positive. In TypeScript, keep the input unsigned with
>>> and build the output with arithmetic doubling; a left shift would coerce the
growing result back to a signed 32-bit number.
Time O(32). Space O(1) — fixed work and one output accumulator.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
964176192