mediumMathArrays & Hashing

Reverse Integer

mediumTime: O(log x)Space: O(1)

The shape of the problem

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?"

Arrays & Hashing Pattern