Reverse Integer

MediumMath · Overflow Handling🧩 Math & GeometryLeetCode #7 ↗Updated

Problem

Given a 32-bit signed integer x, return the number formed by writing its digits in reverse order (the sign stays). If that result falls outside [-231, 231-1], return 0. Assume you may not store 64-bit integers.
Inputx = 123Output321
Inputx = -123Output-321
Inputx = 1534236469Output0 (overflow)

-231 ≤ x ≤ 231-1  ·  trailing zeros vanish (120 → 21)  ·  no 64-bit types

Try it yourself

Java
class Solution {
    public int reverse(int x) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Before doing rev = rev * 10 + d, check whether it would overflow by comparing rev with MAX / 10 (and MIN / 10). Detect overflow before it happens, using only ints.
PatternMath & Geometry

Instinct Digits, factors, slopes or distances hide a formula - find the invariant, then guard against overflow, negatives and floating-point error.

Memory hack Mod peels, gcd reduces, squares compare - and long saves the day. Peel digits with %10, reduce slopes with gcd, compare squared distances.

Open the Math & Geometry guide →

Approaches

Brute ForceString Reverse + Parse

Time O(log x)Space O(log x)

Write the absolute digits to a StringBuilder, reverse them, re-attach the sign and let Integer.parseInt decide: it throws NumberFormatException when the value does not fit in an int, which we map to 0.

Java
public int reverse(int x) {
    String s = Integer.toString(x);
    boolean negative = x < 0;
    if (negative) s = s.substring(1); // strip '-'
    String r = (negative ? "-" : "") + new StringBuilder(s).reverse();
    try {
        return Integer.parseInt(r);
    } catch (NumberFormatException e) {
        return 0; // out of 32-bit range
    }
}

Short and safe, but uses a string and an exception for control flow.

At a glance

LevelApproachTimeSpace
Brute ForceString Reverse + ParseO(log x)O(log x)
BetterMath Reverse in a longO(log x)O(1)
OptimalMath Reverse with Pre-Overflow CheckO(log x)O(1)
Common pitfalls
  • Computing rev * 10 + d first and checking after — the overflow already happened.
  • Using Math.abs(x): abs(-2147483648) is still negative.
  • Returning the overflowed value instead of 0.
Interview tips
  • Ask about the 64-bit restriction early — it rules out the long shortcut.
  • Point out that Java's % keeps the sign, so negatives need no special case.
  • Test the boundaries: 1534236469, -2147483648, 120.
Pattern
Digit peeling + overflow guard → build a number digit by digit under a fixed-width integer limit (e.g. atoi).
My notes saved in this browser