DEV Community

Mahdi Shamlou | Solving LeetCode #7: Reverse Integer — My Math-Based Reversal with Overflow Safety

Hey everyone! Mahdi Shamlou here — continuing my LeetCode classic problems series 🚀

After [#6 Zigzag Conversion (See the list that I solved)], 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!

Mahdi Shamlou | مهدی شاملو

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
Enter fullscreen mode Exit fullscreen mode

My solution:

digit-by-digit reversal with overflow check . I decided to avoid string conversion and do it mathematically — pop digits with % 10, build the reversed number, and most importantly check for overflow before multiplying by 10 and adding the digit.

class Solution:
    def reverse(self, x: int) -> int:

        reversed_x = 0 # create reverse_x to return 

        # Try to Handle the sign separately
        if x >= 0:
            sign = 1
        else:
            sign = -1

        x = abs(x)

        while x > 0:
            digit = x % 10
            x = x // 10

            # checks for overflow before adding the new digit
            # 2**31 - 1 is equals = 2147483647
            # -2**31    is equals = -2147483648

            if reversed_x > (2147483647 - digit) // 10: # but you can use dynamic number calculation like 2**31-1
                return 0
            if reversed_x < (-2147483648 + digit) // 10:
                return 0

            reversed_x = reversed_x * 10 + digit

        return sign * reversed_x
Enter fullscreen mode Exit fullscreen mode

It passes all cases — and feels clean because we catch overflow before it actually happens.

My repo (all solutions are here): GitHub — mahdi0shamlou/LeetCode: Solve LeetCode Problems

Time & Space
Time: O(log |x|) — we process each digit once
Space: O(1) — just a few variables

What about you? Did you also do it mathematically like me? How did you handle the overflow part — did you use constants or 2**31?

Share in the comments — I read everything! 🚀

And honestly… after seeing those overflow cases return 0 correctly and the normal ones reverse perfectly, I just smiled and thought “yes — safe and elegant!” 😂 Here’s me right after submitting:

Mahdi Shamlou | مهدی شاملو

Connect with me:

🔗 LinkedIn: https://www.linkedin.com/in/mahdi-shamlou

📱 Telegram: https://t.me/mahdi_shamlou

📸 Instagram: https://www.instagram.com/mahdi.shamlou

Author: Mahdi Shamlou | مهدی شاملو

Top comments (0)