DEV Community

Hommies
Hommies

Posted on

LeetCode Solution: 7. Reverse Integer

Unlocking LeetCode 7: Reverse Integer (A Beginner's Guide to Digital Flipping!)

Hello Devs! Today, we're diving into a classic LeetCode problem that's perfect for honing your logical thinking and handling tricky integer constraints: Problem 7: Reverse Integer. It sounds simple, but there's a neat catch!

Problem Explanation

We're given a signed 32-bit integer (that's a number that can be positive or negative, fitting within a specific range, roughly -2 billion to +2 billion). Our goal is to return this integer with its digits reversed.

Sounds easy, right? Here's the catch: If reversing the digits causes the number to go outside the valid 32-bit integer range, we must return 0. Also, we can't use 64-bit integers, which means we need to be careful with intermediate results if we were using a fixed-size integer language.

Let's look at some examples:

  • x = 123 becomes 321
  • x = -123 becomes -321 (the sign stays!)
  • x = 120 becomes 21 (leading zeros are dropped when reversing)

Intuition

The "aha!" moment for this problem often comes from realizing that dealing with individual digits of a number is much easier when it's not a number. Think of it: how do you reverse "123"? You literally flip the order. What data type is great for flipping characters? Strings!

So, our core idea is:

  1. Convert the integer to a string.
  2. Reverse the string.
  3. Convert it back to an integer.
  4. Perform the all-important range check.

Approach

Let's break down the steps:

  1. Handle the Sign: Before reversing, we need to know if the original number x was negative. If x is negative, we'll reverse its positive counterpart (e.g., 123 from -123) and then apply the negative sign back at the end.
  2. Convert and Reverse:
    • If x is negative, we first take its absolute value's string representation (str(x)[1:] effectively removes the - sign). Then, we reverse this substring using slicing ([::-1]).
    • If x is positive, we simply convert x to a string (str(x)) and reverse it.
  3. Convert Back to Integer: After reversing the string, we convert it back to an integer using int().
  4. Apply Sign (if needed): If the original x was negative, multiply our res by -1.
  5. The Critical Overflow Check: This is where many solutions fail! We need to check if our res is now outside the [-2^31, 2^31 - 1] range.
    • The maximum 32-bit signed integer is 2**31 - 1.
    • The minimum 32-bit signed integer is -2**31.
    • If res is too large or too small, return 0. Otherwise, return res.

Code

Here's the Python implementation based on our approach:

class Solution:
    def reverse(self, x: int) -> int:
        # Define the 32-bit integer range boundaries
        MAX_INT = 2**31 - 1
        MIN_INT = -2**31

        res = 0
        if x < 0:
            # For negative numbers, remove the '-' sign, reverse, then re-apply '-'
            # Example: -123 -> "123" -> "321" -> -321
            res = int(str(x)[1:][::-1]) * -1
        else:
            # For positive numbers, simply convert to string, reverse, convert back
            # Example: 123 -> "123" -> "321" -> 321
            res = int(str(x)[::-1])

        # Check for 32-bit integer overflow
        if res > MAX_INT or res < MIN_INT:
            return 0

        return res
Enter fullscreen mode Exit fullscreen mode

Time & Space Complexity Analysis

  • Time Complexity: O(log |x|)
    • The operations involve converting the integer to a string, reversing it, and converting it back. The number of digits in x is proportional to log10(|x|). All these string operations take time proportional to the number of digits.
  • Space Complexity: O(log |x|)
    • We create a string representation of x, which uses space proportional to the number of digits in x.

Key Takeaways

  • String Magic: For digit-based problems, converting integers to strings can often simplify reversal or digit manipulation.
  • Edge Cases are Crucial: Always consider negative inputs and, most importantly, the integer overflow/underflow boundaries.
  • Understand Data Types: Be aware of the maximum and minimum values your data types can hold, especially in competitive programming.

Happy coding!


Author Account: p1Hzd8mRM8
Time Published: 2026-05-17 12:06:31

Top comments (0)