Leetcode #7: Reverse Integer
In this guide, we solve Leetcode #7 Reverse Integer in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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 [-231, 231 - 1], then return 0.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Math
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: x = 123
Output: 321
Python Solution
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
Complexity
The time complexity is , where is the absolute value of . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.