Skip to main content
Back to problems
Leetcode
Medium
Math
Simulation
Reverse Integer

Reverse the digits of a signed 32-bit integer, returning 0 if the reversed value would overflow.

Acceptance 81%
Problem Statement

Problem

Given a signed 32-bit integer x, reverse its decimal digits and return the resulting integer.

  • If x is negative, preserve the sign in the result.
  • Leading zeros in the reversed number should be removed automatically.
  • If the reversed value does not fit in the signed 32-bit range [$-2^{31}$, $2^{31}-1$], return 0.

Implement the reversal without using string conversion if possible; the core challenge is handling overflow safely while rebuilding the number digit by digit.

Input Format

  • A single integer x.

Output Format

  • Return the reversed integer, or 0 if the result overflows 32-bit signed integer range.

Constraints

  • 231x2311-2^{31} \le x \le 2^{31} - 1
  • The result must also fit in the same range, otherwise return 0.

Hints

  • Extract digits one at a time using % 10 and / 10.
  • Check for overflow before multiplying by 10 and adding the next digit.
  • Be careful with negative values and languages where integer division truncates toward zero.

Input Format

A single signed 32-bit integer x.

Output Format

The reversed integer, or 0 if reversing x would overflow a signed 32-bit integer.

Constraints

  • 231x2311-2^{31} \le x \le 2^{31} - 1
  • Return 0 when the reversed integer is outside this range.
Examples
Sample cases returned by the problem API.

Example 1

Input

x = 123

Output

321

Explanation

Reversing the digits gives 321, which fits in range.

Example 2

Input

x = -120

Output

-21

Explanation

The reversed digits are 021, which becomes 21, and the sign stays negative.

Show 1 more example

Example 3

Input

x = 1534236469

Output

0

Explanation

The reversed value is 9646324351, which overflows 32-bit signed integer range, so return 0.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.