Mahdi Shamlou | Solving LeetCode #7: Reverse Integer — My Math-Based Reversal with Overflow Safety
Source: Dev.to
Hey everyone! Mahdi Shamlou here — continuing my LeetCode classic problems series 🚀
After solving #6 Zigzag Conversion, today we’re tackling Problem #7 — Reverse Integer — a very common easy/medium question that looks simple at first… until you remember the 32‑bit integer overflow trap!

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 [-2³¹, 2³¹ − 1], then return 0.
Assume the environment does not allow 64‑bit integers.
Examples
Input: x = 123
Output: 321
Input: x = -123
Output: -321
Input: x = 120
Output: 21
Input: x = 0
Output: 0
My Solution
Digit‑by‑digit reversal with overflow check. I avoided string conversion and performed the reversal mathematically — popping digits with % 10, building the reversed number, and checking for overflow before multiplying by 10 and adding the digit.
class Solution:
def reverse(self, x: int) -> int:
reversed_x = 0
# Handle the sign separately
sign = 1 if x >= 0 else -1
x = abs(x)
while x > 0:
digit = x % 10
x //= 10
# Check for overflow before adding the new digit
# 2**31 - 1 = 2147483647
# -2**31 = -2147483648
if reversed_x > (2147483647 - digit) // 10:
return 0
if reversed_x < (-2147483648 + digit) // 10:
return 0
reversed_x = reversed_x * 10 + digit
return sign * reversed_x
The code passes all test cases and feels clean because we catch overflow before it actually happens.
You can find all my solutions in the repository:
GitHub – mahdi0shamlou/LeetCode: Solve LeetCode Problems
Time & Space Complexity
- Time:
O(log |x|)— we process each digit once. - Space:
O(1)— only a few integer variables are used.
Result
After submitting, the overflow cases correctly return 0 and the normal cases reverse perfectly. Here’s a snapshot of the successful submission:
