CodeArchon

mediumBit ManipulationBloombergApple

Integer Mirror

A sign reader reverses the digits of a signed 32-bit integer, returning 0 if the result would overflow.

Given a signed 32-bit integer x, return x with its digits reversed. If reversing causes the value to exceed 32-bit range, return 0.

Choose approach

123
0
Mapstate
r→3
x→12
1/4
Narrationstep 1 of 4

Appended digit → r=3, remaining x=12.

1def reverse(x):
2 sign = -1 if x < 0 else 1
3 x = abs(x)
4 r = 0
5 while x:
6 r = r * 10 + x % 10
7 x //= 10
8 r *= sign
9 return 0 if r < -2**31 or r > 2**31 - 1 else r
Variables
r=3
x=12

How to think about it

  1. No string allocation.
  2. Check overflow BEFORE a 10× that would already exceed range.

Edge cases to catch in interview

  • 0 -> 0.
  • Trailing zeros vanish (1200 -> 21).

Examples

Example 1-321
{"x":-123,"values":[-123]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed