Reverse Integer
LeetCode 7 | Difficulty: Mediumβ
MediumProblem 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)β
| Metric | Value |
|---|---|
| Runtime | 63 ms |
| Memory | N/A |
| Date | 2017-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β
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Discuss the brute force approach first, then optimize. Explain your thought process.