DEV Community

Vansh Aggarwal
Vansh Aggarwal

Posted on

LeetCode Solution: 7. Reverse Integer

🚀 Master LeetCode 7: Reversing Integers Without Breaking the Bank (or Your Code!)

Hey LeetCoders and aspiring developers! 👋 Vansh2710 here, your friendly neighborhood competitive programmer and technical writer. Today, we're diving into a classic LeetCode problem that might seem simple on the surface but hides a crucial detail that trips up many beginners (and even some seasoned folks!): Reverse Integer (Problem 7).

It's a fantastic problem to learn about integer manipulation and, more importantly, how to handle those pesky overflow scenarios. Let's conquer it together!

📖 Problem Explained: The Digit Dilemma

You're given a signed 32-bit integer x. Your task is to return x with its digits reversed. Sounds easy, right?

Here's the catch: If reversing x causes its value to go outside the signed 32-bit integer range (which is [-2^31, 2^31 - 1]), you must return 0. Oh, and you can't use 64-bit integers. This last constraint is key!

Let's look at some examples to get a feel for it:

  • Example 1:

    • Input: x = 123
    • Output: 321 (Simple positive reversal)
  • Example 2:

    • Input: x = -123
    • Output: -321 (Negative numbers reverse similarly, keeping the sign)
  • Example 3:

    • Input: x = 120
    • Output: 21 (Trailing zeros become leading zeros and get dropped)

The core idea seems straightforward, but the "overflow" part is where the real challenge lies!

✨ Intuition: Building Backwards, Digit by Digit

Imagine you have the number 123. How would you "reverse" it manually?

  1. You'd grab the 3.
  2. Then the 2.
  3. Then the 1.

And then you'd put them together as 321.

How can we do this programmatically?

  • Getting the last digit: The modulo operator (%) is our best friend! 123 % 10 gives us 3.
  • Removing the last digit: Integer division (/) comes to the rescue! 123 / 10 gives us 12.
  • Building the reversed number: Let's say we have a reversed_num variable, initially 0.
    • When we get 3: reversed_num = 0 * 10 + 3 = 3.
    • When we get 2: reversed_num = 3 * 10 + 2 = 32.
    • When we get 1: reversed_num = 32 * 10 + 1 = 321.

This "extract-and-build" loop forms the heart of our solution. But wait! What if x is 2147483647 (which is INT_MAX)? Reversing it would give 7463847412, which is much larger than INT_MAX. This is where our overflow check becomes absolutely vital! We need to detect this before it happens.

🧠 Our Step-by-Step Approach

Let's break down the logic into clear, manageable steps:

  1. Initialize reversed_num: We'll need a variable, let's call it reversed_num, initialized to 0. This will store our result as we build it.
  2. Loop While x Has Digits: We'll use a while loop that continues as long as x is not 0. Each iteration will process one digit.
  3. Extract the Last Digit: Inside the loop, get the last digit of x using int digit = x % 10;.
  4. 🚨 CRITICAL OVERFLOW CHECK 🚨: This is the most important part! Before we actually update reversed_num with the new digit, we need to check if doing so would cause an overflow (i.e., exceed INT_MAX or go below INT_MIN).
    • How to check?
      • If reversed_num is already greater than INT_MAX / 10, then multiplying reversed_num by 10 will definitely overflow.
      • If reversed_num is exactly INT_MAX / 10, then adding a digit greater than 7 (since INT_MAX is 2,147,483,647 and 7 is its last digit) will cause an overflow.
      • Similar logic applies for INT_MIN: if reversed_num < INT_MIN / 10 or (reversed_num == INT_MIN / 10 and digit < -8), it will underflow.
    • If any overflow/underflow is detected, immediately return 0 as per the problem statement.
  5. Build reversed_num: If no overflow is detected, safely update reversed_num: reversed_num = reversed_num * 10 + digit;.
  6. Shrink x: Remove the last digit from x by integer division: x /= 10;.
  7. Return Result: Once the loop finishes (meaning x is 0 and all digits have been processed), return the final reversed_num.

✍️ The Code (C++)

Here's the C++ implementation incorporating the logic we just discussed:

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

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

        // Loop until x becomes 0 (all digits processed)
        while (x != 0) {
            // Extract the last digit of x
            int digit = x % 10;

            // --- CRITICAL OVERFLOW CHECK ---
            // This check must happen BEFORE we update `reversed_num`.
            // We're essentially asking: "If I multiply `reversed_num` by 10
            // and add `digit`, will it go out of bounds?"

            // Positive overflow check:
            // 1. If `reversed_num` is already greater than `INT_MAX / 10`,
            //    multiplying by 10 will *definitely* overflow.
            // 2. If `reversed_num` is exactly `INT_MAX / 10`,
            //    adding `digit` will cause overflow IF `digit` is greater than 7.
            //    (Because INT_MAX = 2,147,483,647, so the last digit is 7).
            if (reversed_num > INT_MAX / 10 || (reversed_num == INT_MAX / 10 && digit > 7)) {
                return 0; // Overflow detected, return 0
            }

            // Negative overflow check:
            // 1. If `reversed_num` is already less than `INT_MIN / 10`,
            //    multiplying by 10 will *definitely* underflow.
            // 2. If `reversed_num` is exactly `INT_MIN / 10`,
            //    adding `digit` will cause underflow IF `digit` is less than -8.
            //    (Because INT_MIN = -2,147,483,648, so the last digit is -8).
            if (reversed_num < INT_MIN / 10 || (reversed_num == INT_MIN / 10 && digit < -8)) {
                return 0; // Underflow detected, return 0
            }

            // If no overflow, safely build the reversed number
            reversed_num = reversed_num * 10 + digit;

            // Remove the last digit from x
            x /= 10;
        }

        // All digits processed, return the final reversed number
        return reversed_num;
    }
};
Enter fullscreen mode Exit fullscreen mode

⏱️ Time & Space Complexity Analysis

Time Complexity: O(log |x|)

Why O(log |x|)?
Because in each iteration of our while loop, we're effectively removing one digit from x (by dividing x by 10). The number of digits in an integer x is proportional to log10 |x|. For a 32-bit integer, the maximum number of digits is around 10 (since 2^31 - 1 is roughly 2 * 10^9). So, even for the largest possible x, the loop runs a very small, constant number of times. It's incredibly efficient!

Space Complexity: O(1)

We are only using a few extra variables (reversed_num, digit, etc.) whose memory usage does not change with the input size x. Therefore, the space complexity is constant.

🎯 Key Takeaways

  • Digit Manipulation Power Duo: Remember num % 10 to get the last digit and num / 10 to remove it. They are fundamental for many integer-based problems.
  • The Dreaded Overflow: Always be mindful of integer limits, especially in problems specifying fixed-size types (like 32-bit integers).
  • Proactive Overflow Checks: The golden rule is to check for potential overflow before performing the operation that might cause it. Don't wait for your program to crash!
  • Building Numbers: The pattern result = result * 10 + digit is a common and powerful technique for constructing numbers from their digits.
  • Edge Cases Matter: Think about negative numbers and numbers ending in zero (like 120 becoming 21). Our solution handles these gracefully!

This problem is a fantastic way to solidify your understanding of basic arithmetic operations and introduce you to the critical concept of overflow handling in programming. Keep practicing, and you'll be a LeetCode master in no time!


Author: Vansh2710

Published: 2026-04-24 00:33:03

Top comments (0)