DEV Community

Vansh Aggarwal
Vansh Aggarwal

Posted on

LeetCode Solution: 7. Reverse Integer

Cracking LeetCode 7: Reversing Integers Without Breaking the Bank (or the Integer Limit!) πŸš€

Hey everyone! Vansh here, ready to dive into another classic LeetCode problem that might seem simple on the surface but hides a crucial twist: integer overflow. Today, we're tackling LeetCode Problem 7: Reverse Integer.

This problem is a fantastic stepping stone for beginners because it teaches you not just about basic arithmetic manipulations but also about handling the often-overlooked boundaries of data types. Let's get cracking!


Understanding the Challenge: Reverse Integer πŸ”„

Imagine you have a number, say 123. The goal is to reverse its digits to get 321. Sounds easy, right? What if it's -123? Then it should be -321. And 120 should become 21 (leading zeros are dropped).

Here's the catch: We're dealing with a signed 32-bit integer. This means our number x can range from -2,147,483,648 (which is -231) to 2,147,483,647 (which is 231 - 1).

If, after reversing the digits, the number goes outside this specific range, we're supposed to return 0. And to make things spicier, we cannot use 64-bit integers to store our result temporarily. This constraint forces us to be clever with our overflow checks!

Let's look at the examples:

  • Input: x = 123 Output: 321 (Perfectly within range)
  • Input: x = -123 Output: -321 (Also good!)
  • Input: x = 120 Output: 21 (Trailing zero vanishes, as expected)
  • Consider this tricky one: If x = 2147483647 (the maximum 32-bit integer), reversing it would give 7463847412. This number is much larger than 2147483647, so we should return 0. This is where the overflow check comes in!

The "Aha!" Moment: Intuition ✨

How do we reverse a number, digit by digit? Think about how you'd get the last digit of a number and then remove it.

  1. Get the last digit: The modulo operator (%) is our best friend here! 123 % 10 gives 3.
  2. Remove the last digit: Integer division (/) does the trick! 123 / 10 gives 12.
  3. Build the reversed number: If our reversed_num starts at 0, and we get a digit, we can do reversed_num = reversed_num * 10 + digit.
    • Start: reversed_num = 0
    • x = 123, digit = 3. reversed_num = 0 * 10 + 3 = 3. x = 12.
    • x = 12, digit = 2. reversed_num = 3 * 10 + 2 = 32. x = 1.
    • x = 1, digit = 1. reversed_num = 32 * 10 + 1 = 321. x = 0.
    • Loop ends! We have 321.

This basic process works perfectly. But remember the overflow constraint? That's the real "aha!" moment. We can't just let reversed_num * 10 + digit happen blindly. We need to check for potential overflow before it occurs, because once an integer overflows, its value becomes unpredictable (or wraps around, which is incorrect for this problem).

The trick for overflow is to check if reversed_num is already too large (or too small) such that multiplying it by 10 or adding the next digit would push it past INT_MAX or INT_MIN. Specifically, we check if reversed_num > INT_MAX / 10 or reversed_num < INT_MIN / 10. If reversed_num equals these thresholds, we need a final check on the digit.


Step-by-Step Approach πŸšΆβ€β™‚οΈ

Let's outline our robust approach:

  1. Initialize result: We'll need a variable, let's call it result, to store our reversed number. Initialize it to 0.
  2. Loop while x is not 0: We continue this process until all digits from x have been extracted.
  3. Extract the last digit:
    • int digit = x % 10;
  4. Crucial Overflow Check (before updating result!): This is the heart of handling the constraints.
    • Positive Overflow Check:
      • If result is already greater than INT_MAX / 10, then multiplying result by 10 will definitely overflow. Return 0.
      • If result is exactly equal to INT_MAX / 10, then we need to check the digit. INT_MAX ends in 7 (2,147,483,647). If our digit is greater than 7 (i.e., 8 or 9), then result * 10 + digit will overflow. Return 0.
    • Negative Overflow Check:
      • If result is already less than INT_MIN / 10, then multiplying result by 10 will definitely underflow. Return 0.
      • If result is exactly equal to INT_MIN / 10, then we need to check the digit. INT_MIN ends in 8 (-2,147,483,648). If our digit is less than -8 (i.e., -9), then result * 10 + digit will underflow. Return 0.
  5. Build the reversed number:
    • result = result * 10 + digit;
  6. Remove the last digit from x:
    • x = x / 10;
  7. Return result: Once the loop finishes, result holds our fully reversed integer (or 0 if an overflow was detected).

This approach handles positive numbers, negative numbers, and most importantly, gracefully manages the overflow conditions without needing 64-bit integers!


The Code πŸ’»

Here's the C++ implementation using the INT_MAX and INT_MIN constants found in <limits.h> (or <climits> for C++):

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

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

        while (x != 0) {
            // Step 1: Extract the last digit
            int digit = x % 10;

            // Step 2: Crucial Overflow Check BEFORE updating result
            // Check for potential positive overflow:
            // If result is already greater than INT_MAX / 10, then multiplying by 10 will surely overflow.
            // If result is exactly INT_MAX / 10, then adding a digit > 7 will cause overflow (since INT_MAX is 2,147,483,647).
            if (result > INT_MAX / 10 || (result == INT_MAX / 10 && digit > 7)) {
                return 0;
            }

            // Check for potential negative overflow (underflow):
            // If result is already less than INT_MIN / 10, then multiplying by 10 will surely underflow.
            // If result is exactly INT_MIN / 10, then adding a digit < -8 will cause underflow (since INT_MIN is -2,147,483,648).
            if (result < INT_MIN / 10 || (result == INT_MIN / 10 && digit < -8)) {
                return 0;
            }

            // Step 3: Build the reversed number
            result = result * 10 + digit;

            // Step 4: Remove the last digit from the original number
            x = x / 10;
        }

        return result; // Return the final reversed integer
    }
};

Enter fullscreen mode Exit fullscreen mode

Time & Space Complexity Analysis β±οΈπŸ“

  • Time Complexity: O(log |x|)
    We iterate through the digits of the input number x. The number of digits in an integer x is proportional to log10(|x|). For example, a 1-digit number takes 1 iteration, a 2-digit number takes 2 iterations, and so on. Since we process each digit exactly once, the time complexity is logarithmic with respect to the absolute value of x.

  • Space Complexity: O(1)
    We use a fixed number of variables (result, digit). The amount of memory used does not grow with the size of the input x. Hence, the space complexity is constant.


Key Takeaways πŸ’‘

  • Digit Manipulation: The modulo (% 10) and integer division (/ 10) operators are your go-to tools for extracting and removing digits from an integer.
  • Building Numbers: To construct a number from individual digits, multiply the current result by 10 and add the new digit.
  • Overflow is Critical: Always be mindful of integer limits, especially in competitive programming problems where data type constraints are common.
  • Pre-emptive Checks: For overflow problems where a larger data type isn't allowed, check for overflow before performing operations that might cause it. The INT_MAX / 10 and INT_MIN / 10 trick is a standard way to do this.

This problem is a fantastic blend of basic arithmetic and careful edge-case handling. Master it, and you'll be well on your way to tackling more complex LeetCode challenges!

Happy coding! πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»


Author Account: Vansh2710
Published: 2026-04-24 01:21:55

Top comments (0)