Reverse Integer

Medium Math

Problem

Given a 32-bit signed integer x, return x with its digits reversed. If reversing causes overflow, return 0.

Example 1 Input: 123 Output: 321
Example 2 Input: -123 Output: -321
Example 3 Input: 120 Output: 21
Example 4 Input: 1534236469 Output: 0 Explain: overflows

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class Solution:
    def reverse(self, x):
        sign = -1 if x < 0 else 1
        r = sign * int(str(abs(x))[::-1])
        return r if -2**31 <= r <= 2**31 - 1 else 0

Java

class Solution {
    public int reverse(int x) {
        int r = 0;
        while (x != 0) {
            int d = 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;
            x /= 10;
        }
        return r;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Reverse Integer interactively → ← All solutions