Problem Statement

Reverse Integer

You are given a whole number x, and you need to flip its digits around. So 123 becomes 321. The sign stays put, so a negative number stays negative. There is one catch. A computer can only hold numbers up to a certain size. Here the limit is a "signed 32-bit integer," which is just a fixed-size box that fits numbers from -2^31 up to 2^31 - 1 (about -2.1 billion to 2.1 billion). If the flipped number would not fit in that box, you return 0 instead. The tool we use here is plain arithmetic. We peel digits off the end of x one at a time and stack them onto a new number, checking before each step that we are not about to spill out of the box.

mediumMathMath & Number TheoryTime: O(log x) · Space: O(1)

Translate the prompt

Reverse the digits of a signed 32-bit integer. If the reversed value overflows the 32-bit signed range, return 0.

Signals to notice

digit-by-digit buildmodulus and division32-bit overflow guard

Brute force first

Convert to string, reverse the string, parse back to int. Correct, but hides the overflow case and has to treat the sign specially.

The key insight

Reversing base-10 is just repeatedly moving the ones-digit of the input onto the ones-digit of a new number. No string conversion needed, and the sign rides along with integer arithmetic in languages that allow negative modulus.

Trace it on x=123

result=0   x=123  digit=3  result=0*10+3=3   x=12
result=3   x=12   digit=2  result=3*10+2=32  x=1
result=32  x=1    digit=1  result=32*10+1=321 x=0
x==0 → return 321

What must stay true

After k iterations, `result` equals the integer formed by the last k digits of the original input, in reverse.

Shape of the loop

result = 0
while x != 0:
  d = x % 10
  if result would overflow after *10+d: return 0
  result = result*10 + d
  x //= 10
return result

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Overflow-checking after the multiplication. `result*10 + digit` may already overflow the 32-bit bound by the time you inspect it. Check before: "would this push result past INT_MAX/10?"

Math & Number Theory Pattern