Skip to main content

Reverse Integer

LeetCode 7 | Difficulty: Medium​

Medium

Problem Description​

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Constraints:

- `-2^31 <= x <= 2^31 - 1`

Topics: Math


Approach​

Mathematical​

Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.

When to use

Problems with clear mathematical structure, counting, number properties.


Solutions​

Solution 1: C# (Best: 63 ms)​

MetricValue
Runtime63 ms
MemoryN/A
Date2017-07-16
Solution
public class Solution {
public int Reverse(int x) {
bool isNeg = false;
if (x < 0)
{
isNeg = true;
}
int rev = 0;
while (x != 0)
{
try
{
int rem = x % 10;
x /= 10;
rev = checked(rev * 10 + rem);
}
catch (OverflowException)
{
return 0;
}

}

return rev;
}
}

Complexity Analysis​

ApproachTimeSpace
Solution$O(n)$$O(1) to O(n)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.