DEV Community

Vansh Aggarwal
Vansh Aggarwal

Posted on

LeetCode Solution: 7. Reverse Integer

Reversing Integers: Tackling LeetCode Problem 7 with Confidence!

Hey there, future coding rockstars! 👋 Vansh here, ready to demystify another classic LeetCode problem that might seem simple on the surface but hides a clever trick: Problem 7: Reverse Integer.

Don't let the "easy" tag fool you; this problem is a fantastic way to sharpen your understanding of integer manipulation and, more importantly, handle those pesky edge cases like a pro! Let's dive in!


The Challenge: What's the Goal?

Imagine you have a number, say 123. Your mission, should you choose to accept it, is to reverse its digits to get 321. Sounds straightforward, right? But there's a catch (or two!):

  1. Signed 32-bit integer: We're dealing with numbers that can be positive or negative, and they live within a specific computer memory limit: [-2^31, 2^31 - 1].
    • Minimum: -2,147,483,648
    • Maximum: 2,147,483,647
  2. Overflow Protection: If reversing the number makes it too big (or too small) to fit within this 32-bit range, we must return 0. This is the sneaky part!
  3. No 64-bit integers: We can't just convert to a larger data type to avoid overflow during intermediate steps. We have to be smart with our 32-bit integers throughout.

Let's look at a few examples:

  • Example 1: x = 123 -> Output: 321 (Simple positive)
  • Example 2: x = -123 -> Output: -321 (Simple negative, sign should be preserved)
  • Example 3: x = 120 -> Output: 21 (Trailing zeros disappear in the reversal)

See? It's not just flipping digits; it's about handling signs and staying within bounds!


The "Aha!" Moment: How Do We Even Reverse Digits?

Before we jump to the overflow puzzle, let's figure out how to reverse digits of an integer. Think about how you'd do it manually:

To get the last digit of a number, we can use the modulo operator (%) with 10.

  • 123 % 10 gives 3
  • 12 % 10 gives 2
  • 1 % 10 gives 1

To remove the last digit from a number, we can use integer division (/) by 10.

  • 123 / 10 gives 12
  • 12 / 10 gives 1
  • 1 / 10 gives 0

Now, how do we build the reversed number? We start with 0 and, for each digit we extract, we:

  1. Multiply our current reversed_number by 10.
  2. Add the new digit.

Let's trace x = 123:

Step x (original) digit (x % 10) reversedNum (reversedNum * 10 + digit)
Start 123 - 0
1 123 3 0 * 10 + 3 = 3
2 12 2 3 * 10 + 2 = 32
3 1 1 32 * 10 + 1 = 321
End 0 - 321

This iterative process, using modulo and division within a while loop (which continues as long as x is not 0), is the core intuition!


The Smart Approach: Handling Overflow!

The simple digit-reversal logic works perfectly until we hit the 32-bit integer limits. The trick is to check for potential overflow before we perform the operation that might cause it.

Imagine reversedNum is currently 214748364. If the next digit is 7, 214748364 * 10 + 7 would be 2147483647, which is exactly INT_MAX (the maximum 32-bit integer). Perfect!

But what if the next digit was 8? 214748364 * 10 + 8 would be 2147483648, which is INT_MAX + 1! This is an overflow!

So, we need a check:

  • For Positive Overflow:

    • If reversedNum is already greater than INT_MAX / 10, multiplying it by 10 will definitely overflow.
    • If reversedNum is equal to INT_MAX / 10, we need to check the digit. If digit is greater than 7, it will cause an overflow. (Since INT_MAX ends in 7: 2,147,483,647).
  • For Negative Overflow:

    • If reversedNum is already less than INT_MIN / 10, multiplying it by 10 will definitely overflow (become too negative).
    • If reversedNum is equal to INT_MIN / 10, we need to check the digit. If digit is less than -8, it will cause an overflow. (Since INT_MIN ends in 8: -2,147,483,648).

These checks must happen before the line reversedNum = reversedNum * 10 + digit;. If an overflow is detected, we immediately return 0.


The Code (C++)

Let's put it all together into a clean, working solution. We'll use INT_MAX and INT_MIN constants available in <limits.h> for the maximum and minimum values of a 32-bit integer.

#include <limits.h> // Required for INT_MAX and INT_MIN

class Solution {
public:
    int reverse(int x) {
        int reversedNum = 0; // This will store our reversed number

        // Loop continues as long as there are digits left in x
        while (x != 0) {
            // Step 1: Extract the last digit of x
            // For positive x, x % 10 gives the last digit (e.g., 123 % 10 = 3)
            // For negative x, x % 10 gives the last digit (e.g., -123 % 10 = -3)
            int digit = x % 10;

            // Step 2: Critical Overflow Check BEFORE updating reversedNum
            // Check for potential positive overflow
            // If reversedNum is already too large (e.g., > INT_MAX / 10)
            // OR if reversedNum is exactly INT_MAX / 10 AND the next digit would push it over (digit > 7 for INT_MAX = ...7)
            if (reversedNum > INT_MAX / 10 || (reversedNum == INT_MAX / 10 && digit > 7)) {
                return 0; // Overflow detected, return 0 as per problem statement
            }

            // Check for potential negative overflow
            // If reversedNum is already too small (e.g., < INT_MIN / 10)
            // OR if reversedNum is exactly INT_MIN / 10 AND the next digit would push it over (digit < -8 for INT_MIN = ...8)
            if (reversedNum < INT_MIN / 10 || (reversedNum == INT_MIN / 10 && digit < -8)) {
                return 0; // Overflow detected, return 0
            }

            // Step 3: Build the reversed number
            // Multiply current reversedNum by 10 to shift digits left, then add the new digit
            reversedNum = reversedNum * 10 + digit;

            // Step 4: Remove the last digit from x
            // Integer division by 10 truncates the last digit
            x /= 10;
        }

        // Once x becomes 0, all digits have been processed, return the final reversed number
        return reversedNum;
    }
};
Enter fullscreen mode Exit fullscreen mode

Time and Space Complexity Analysis

  • Time Complexity: O(log |x|)

    • The number of iterations in our while loop is proportional to the number of digits in the input integer x.
    • Since x is a 32-bit integer, it has at most 10 digits (e.g., 2,147,483,647).
    • Each iteration involves a constant number of operations (modulo, division, multiplication, addition, comparisons).
    • Therefore, the time complexity is logarithmic with respect to the absolute value of x.
  • Space Complexity: O(1)

    • We are only using a few fixed-size integer variables (x, reversedNum, digit).
    • The amount of memory used does not grow with the input size.

Key Takeaways

  1. Digit Manipulation: The core pattern of num % 10 for getting the last digit and num / 10 for removing it is fundamental for many integer-based problems.
  2. Overflow Awareness: This problem is a prime example of why you need to be mindful of integer limits. Don't assume numbers will always fit!
  3. Pre-computation Checks: The crucial lesson here is to check for overflow before performing the operation that might cause it. This often involves checking against INT_MAX / 10 or INT_MIN / 10.
  4. Edge Cases: Remember to consider 0, single-digit numbers, and the maximum/minimum possible integer values as test cases.

This problem is a fantastic stepping stone in your LeetCode journey. It teaches you practical skills for dealing with data types and their limitations. Keep practicing, and you'll be solving even tougher challenges in no time! Happy coding!


Authored by Vansh2710 | Published: 2026-04-24 00:24:13

Top comments (0)