Command Palette

Search for a command to run...

Problem 39.6 · Math for Coding InterviewsMedium

Reverse Integer

What it teaches: Digit extraction with an overflow check before each step.

Practise it on judges as “Reverse Integer”.

In plain words

Reverse the digits of a number, keeping the sign: -123 becomes -321. Peel off the last digit with % 10 and stick it on the end of the answer with × 10 +. Before each push, check the answer will not grow past the biggest (or smallest) number a 32-bit int can hold; if it would, return 0.

Return the reversed number, or 0 on overflow. Example: x = -123 → -321.

The problem

Reverse the digits of a 32-bit signed integer. Return 0 if the result overflows. Don't use 64-bit integers.

Example 1

Input: x = -123
Output: -321

Example 2

Input: x = 1534236469
Output: 0

Constraints

  • −2³¹ ≤ x ≤ 2³¹ − 1

Pattern clues in the wording

  • → Digits
  • → Overflow must be detected

These clues point to Number Theory and Combinatorics: GCD, primes, modular arithmetic, fast power and counting formulas that turn loops into a few lines of math.

Stuck? Take one hint at a time

Solution · starter
class Solution {
    public int reverse(int x) {
        return 0;
    }
}

Write your solution locally or in your editor for now. Pick Java, Python, C++, JavaScript or Go above: every solution on this page switches with it. The in-browser runner will run these tests right here.

Test cases

#InputExpected
1
x = 123
321
2
x = -123
-321
3
x = 120
21

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Pop and push digits

Time O(log x) Space O(1)

d = x % 10; x /= 10; check bounds; r = r × 10 + d. Java's % keeps the sign, so negatives work unchanged.

▶ Dry run: Pop the last digit, push it on the answerx = -123
-1
0
-2
1
-3
2

vars(vars)

x: -123r: 0

Step 1/4In Java, -123 % 10 is -3, so the digits come out negative and the sign takes care of itself.

Approach 1
class Solution {
    public int reverse(int x) {
        int r = 0;
        while (x != 0) {
            int d = x % 10;
            x /= 10;
            if (r > Integer.MAX_VALUE / 10 || (r == Integer.MAX_VALUE / 10 && d > 7)) return 0;
            if (r < Integer.MIN_VALUE / 10 || (r == Integer.MIN_VALUE / 10 && d < -8)) return 0;
            r = r * 10 + d;
        }
        return r;
    }
}

Verdict: Overflow check without long.

Before you submit

Edge cases and common mistakes

Test these inputs

  • Trailing zeros (120 → 21)
  • Integer.MIN_VALUE
  • Reversal that overflows

Mistakes people make

  • Checking overflow after multiplying (the damage is done).

Interview

Follow-up questions

How would you do String to Integer (atoi) safely?