LeetCode Problem Workspace

Reverse Integer

Reverse Integer challenges you to invert the digits of a signed 32-bit integer, handling overflow and negative values carefully.

category

1

Topics

code_blocks

9

Code langs

hub

3

Related

Practice Focus

Medium · Math-driven solution strategy

bolt

Answer-first summary

Reverse Integer challenges you to invert the digits of a signed 32-bit integer, handling overflow and negative values carefully.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Math-driven solution strategy

Try AiBox Copilotarrow_forward

To solve Reverse Integer efficiently, extract digits one by one and build the reversed number while checking for 32-bit overflow. Handle negative numbers by preserving the sign and immediately returning 0 if reversing causes an overflow. This approach uses constant space and logarithmic time relative to the number of digits.

Problem Statement

Given a signed 32-bit integer x, return its digits reversed. If the reversed value exceeds the 32-bit signed integer range [-2^31, 2^31 - 1], return 0. The environment does not support storing 64-bit integers.

For example, reversing 123 yields 321, reversing -123 yields -321, and reversing 120 yields 21. Implement a solution that carefully handles overflow and negative inputs while following a math-driven approach.

Examples

Example 1

Input: x = 123

Output: 321

Example details omitted.

Example 2

Input: x = -123

Output: -321

Example details omitted.

Example 3

Input: x = 120

Output: 21

Example details omitted.

Constraints

  • -231 <= x <= 231 - 1

Solution Approach

Digit Extraction with Overflow Check

Iteratively extract the last digit using modulo 10, append it to a reversed number, and check if appending will exceed 32-bit bounds before each step. Stop and return 0 on potential overflow.

Sign Preservation

Maintain the sign of the original number by multiplying the reversed digits by -1 if the original number is negative. Ensure that negative overflow is also checked.

Constant Space Implementation

Avoid using arrays or string conversions to store intermediate digits. Build the reversed number incrementally using only integer arithmetic to achieve O(1) space complexity.

Complexity Analysis

Metric Value
Time O(\log(x))
Space O(1)

Reversing digits requires processing each digit once, resulting in O(log(x)) time since the number of digits in x is proportional to log10(x). Space remains O(1) because no extra storage is needed beyond a few integer variables.

What Interviewers Usually Probe

  • Expect discussion about handling overflow conditions explicitly.
  • Clarify whether negative numbers should retain their sign after reversal.
  • Look for solutions that avoid converting integers to strings.

Common Pitfalls or Variants

Common pitfalls

  • Failing to check for 32-bit overflow before updating the reversed number.
  • Incorrectly handling negative integers or losing the negative sign.
  • Using string conversion which may exceed memory constraints or bypass math-driven strategy.

Follow-up variants

  • Reversing digits in a 64-bit integer while ensuring 64-bit overflow is handled.
  • Counting how many digits can be reversed before reaching overflow.
  • Reversing only the even or odd digits of a number while preserving their positions.

FAQ

What is the best way to reverse an integer without causing overflow?

Extract digits one at a time using modulo and division, build the reversed number incrementally, and check for overflow before each append.

How do I handle negative integers in Reverse Integer?

Preserve the sign of the original number, multiply the reversed digits by -1, and ensure negative overflow checks are applied.

Can I convert the integer to a string to reverse it?

Using strings bypasses the math-driven pattern and may violate space constraints; integer arithmetic is preferred for GhostInterview solutions.

What is the time complexity of the Reverse Integer solution?

Time complexity is O(log(x)) since each digit is processed once, where the number of digits is proportional to log10(x).

Why is checking for overflow before appending each digit important?

Appending without checking can silently exceed 32-bit limits, causing incorrect results or undefined behavior in a math-driven integer reversal.

terminal

Solution

Solution 1: Mathematics

Let's denote $mi$ and $mx$ as $-2^{31}$ and $2^{31} - 1$ respectively, then the reverse result of $x$, $ans$, needs to satisfy $mi \le ans \le mx$.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def reverse(self, x: int) -> int:
        ans = 0
        mi, mx = -(2**31), 2**31 - 1
        while x:
            if ans < mi // 10 + 1 or ans > mx // 10:
                return 0
            y = x % 10
            if x < 0 and y > 0:
                y -= 10
            ans = ans * 10 + y
            x = (x - y) // 10
        return ans
Reverse Integer Solution: Math-driven solution strategy | LeetCode #7 Medium