LeetCode #7: Reverse Integer
Reverse the digits of an integer — but handle overflow and negative signs correctly.
The Problem
Given a signed 32-bit integer x
, return x
with its digits reversed.
If the reversed integer overflows (outside [-2^31, 2^31 - 1]
), return 0
.
Examples
Input: 123 → Output: 321 (321)
Input: -123 → Output: -321 (Keep the negative sign)
Input: 120 → Output: 21 (Remove trailing zeros after reversal)
Input: 1534236469 → Output: 0 (Reversed value (9646324351) > 2^31-1 → overflow → return 0)
Step-by-Step: How to Reverse
We can reverse the digits by repeatedly extracting the last digit:
- Get the last digit:
x % 10
- Add it to the result:
reversed = reversed * 10 + digit
- Remove the last digit:
x = Math.trunc(x / 10)
- Repeat until
x === 0
- Preserve the sign at the end
✅ Solution (JavaScript)
var reverse = function(x) {
const INT_MAX = 2 ** 31 - 1; // 2147483647
const INT_MIN = -(2 ** 31); // -2147483648
let reversed = 0;
const isNegative = x < 0;
x = Math.abs(x);
while (x !== 0) {
const digit = x % 10;
x = Math.trunc(x / 10);
// Check for overflow before multiplying
if (reversed > Math.floor(INT_MAX / 10)) {
return 0;
}
reversed = reversed * 10 + digit;
}
// Restore sign
if (isNegative) reversed = -reversed;
// Final overflow check
if (reversed < INT_MIN || reversed > INT_MAX) {
return 0;
}
return reversed;
};
⚠️ Why Check Overflow Before Multiplying?
We can't check reversed * 10 + digit > INT_MAX
because that operation itself might overflow!
Instead, we check:
if (reversed > Math.floor(INT_MAX / 10)) {
return 0;
}
This is safe because Math.floor(INT_MAX / 10) = 214748364
Try It: Digit Reversal Animation
Watch how each digit is extracted and built into the reversed number.
Digit Reversal Animator
Watch each digit move to the front
0
🌍 Real-World Applications
Reversing digits or checking overflow is more common than you think.
Input Sanitization
When parsing user input (e.g. phone numbers, IDs), systems reverse-check formats or detect tampering by validating digit patterns.
Security: Buffer Overflow Protection
In C/C++, overflow causes crashes or exploits. Modern systems use bounds checks — just like we did — to prevent memory corruption.
Financial Systems
Account numbers, checksums (like Luhn algorithm), and routing codes often involve digit reversal or modular math.
Game Development
Puzzles like "reverse the number" or palindrome checks use this logic. Great for math-based mini-games.
💡 Fun Fact: The largest 32-bit signed integer is 2,147,483,647
. On January 19, 2038, systems using 32-bit time will overflow — known as the Year 2038 Problem.
Summary
This problem teaches how to safely manipulate integers, handle edge cases, and prevent overflow — skills essential in systems programming, security, and embedded software.