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 = 123Output:321(Perfectly within range) - Input:
x = -123Output:-321(Also good!) - Input:
x = 120Output:21(Trailing zero vanishes, as expected) - Consider this tricky one: If
x = 2147483647(the maximum 32-bit integer), reversing it would give7463847412. This number is much larger than2147483647, so we should return0. 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.
- Get the last digit: The modulo operator (
%) is our best friend here!123 % 10gives3. - Remove the last digit: Integer division (
/) does the trick!123 / 10gives12. - Build the reversed number: If our
reversed_numstarts at0, and we get adigit, we can doreversed_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.
- Start:
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:
- Initialize
result: We'll need a variable, let's call itresult, to store our reversed number. Initialize it to0. - Loop while
xis not0: We continue this process until all digits fromxhave been extracted. - Extract the last digit:
-
int digit = x % 10;
-
- Crucial Overflow Check (before updating
result!): This is the heart of handling the constraints.- Positive Overflow Check:
- If
resultis already greater thanINT_MAX / 10, then multiplyingresultby 10 will definitely overflow. Return0. - If
resultis exactly equal toINT_MAX / 10, then we need to check thedigit.INT_MAXends in7(2,147,483,647). If ourdigitis greater than7(i.e.,8or9), thenresult * 10 + digitwill overflow. Return0.
- If
- Negative Overflow Check:
- If
resultis already less thanINT_MIN / 10, then multiplyingresultby 10 will definitely underflow. Return0. - If
resultis exactly equal toINT_MIN / 10, then we need to check thedigit.INT_MINends in8(-2,147,483,648). If ourdigitis less than-8(i.e.,-9), thenresult * 10 + digitwill underflow. Return0.
- If
- Positive Overflow Check:
- Build the reversed number:
-
result = result * 10 + digit;
-
- Remove the last digit from
x:-
x = x / 10;
-
- Return
result: Once the loop finishes,resultholds our fully reversed integer (or0if 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
}
};
Time & Space Complexity Analysis β±οΈπ
Time Complexity: O(log |x|)
We iterate through the digits of the input numberx. The number of digits in an integerxis proportional tolog10(|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 ofx.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 inputx. 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 / 10andINT_MIN / 10trick 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)