Reverse Integer

Medium · rating 1150 · math

Read an integer n. Print its digits reversed, preserving the sign and dropping leading zeros (e.g. 12021, -45-54).

Editorial

Reverse Integer is a common math interview question: reverse the digits of a signed integer, preserving the sign and dropping leading zeros (120 → 21).

Approach

Peel digits off the end with n % 10 and rebuild with res = res*10 + digit, remembering the sign. Because the result is built numerically, trailing zeros vanish on their own.

sign = -1 if n < 0 else 1
n = abs(n); res = 0
while n:
    res = res*10 + n % 10
    n //= 10
return sign * res

Watch out

In fixed-width languages, guard against 32-bit overflow of the reversed value.

Complexity

Time: O(d) in the number of digits. Space: O(1).

Open Reverse Integer in Code Arena →