🚀 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)
- Input:
-
Example 2:
- Input:
x = -123 - Output:
-321(Negative numbers reverse similarly, keeping the sign)
- Input:
-
Example 3:
- Input:
x = 120 - Output:
21(Trailing zeros become leading zeros and get dropped)
- Input:
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?
- You'd grab the
3. - Then the
2. - 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 % 10gives us3. - Removing the last digit: Integer division (
/) comes to the rescue!123 / 10gives us12. - Building the reversed number: Let's say we have a
reversed_numvariable, initially0.- 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.
- When we get
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:
- Initialize
reversed_num: We'll need a variable, let's call itreversed_num, initialized to0. This will store our result as we build it. - Loop While
xHas Digits: We'll use awhileloop that continues as long asxis not0. Each iteration will process one digit. - Extract the Last Digit: Inside the loop, get the last digit of
xusingint digit = x % 10;. - 🚨 CRITICAL OVERFLOW CHECK 🚨: This is the most important part! Before we actually update
reversed_numwith the new digit, we need to check if doing so would cause an overflow (i.e., exceedINT_MAXor go belowINT_MIN).- How to check?
- If
reversed_numis already greater thanINT_MAX / 10, then multiplyingreversed_numby10will definitely overflow. - If
reversed_numis exactlyINT_MAX / 10, then adding adigitgreater than7(sinceINT_MAXis2,147,483,647and7is its last digit) will cause an overflow. - Similar logic applies for
INT_MIN: ifreversed_num < INT_MIN / 10or (reversed_num == INT_MIN / 10anddigit < -8), it will underflow.
- If
- If any overflow/underflow is detected, immediately return
0as per the problem statement.
- How to check?
- Build
reversed_num: If no overflow is detected, safely updatereversed_num:reversed_num = reversed_num * 10 + digit;. - Shrink
x: Remove the last digit fromxby integer division:x /= 10;. - Return Result: Once the loop finishes (meaning
xis0and all digits have been processed), return the finalreversed_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;
}
};
⏱️ 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 % 10to get the last digit andnum / 10to 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 + digitis a common and powerful technique for constructing numbers from their digits. - Edge Cases Matter: Think about negative numbers and numbers ending in zero (like
120becoming21). 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)