Reverse Integer
Pop digit (mod 10) with overflow check
TimeO(log₁₀ n)SpaceO(1)Good solution
Integer-only arithmetic, no log or float. Single loop with one digit extraction and one overflow check per step. Correct bounds: positive result ≤ 2³¹−1, negative magnitude ≤ 2³¹. Standard interview solution.
Code
1const INT32_MAX = 2 ** 31 - 1;
2const INT32_MIN = -(2 ** 31);
3
4/**
5 * Reverse integer digits. Returns 0 if the result would overflow 32-bit signed range.
6 * Classic approach: repeatedly "pop" the last digit (x % 10) and "push" onto result (result * 10 + digit).
7 * Overflow: check before growing result, using integer thresholds (no log10 or float).
8 */
9function reverse(x: number): number {
10 let n = Math.abs(x);
11 let result = 0;
12
13 while (n > 0) {
14 const digit = n % 10;
15 n = Math.floor(n / 10);
16
17 // Positive result must stay <= INT32_MAX. So result * 10 + digit <= INT32_MAX
18 // => result <= (INT32_MAX - digit) / 10. Use integer check without floating point.
19 const maxAllowed = x < 0
20 ? Math.floor((-(INT32_MIN) - digit) / 10) // for negative: result <= 2^31, so (2^31 - digit) / 10
21 : Math.floor((INT32_MAX - digit) / 10);
22
23 if (result > maxAllowed) return 0;
24 result = result * 10 + digit;
25 }
26
27 return x < 0 ? -result : result;
28}
29
30console.log(reverse(0));
31console.log(reverse(123));
32console.log(reverse(-123));
33console.log(reverse(120));
34console.log(reverse(1534236469)); // overflow -> 0
35console.log(reverse(-2147483648)); // -8463847412 reversed = -2147483648, valid
36Animation
Examples
reverse(123) =321
reverse(-123) =-321
reverse(0) =0
reverse(120) =21