Home
DSA Patterns
Bit Manipulation
Reverse Integer
Reverse Integer
Reverse the digits of a 32-bit integer by popping the last digit and pushing it onto the result, checking for overflow before each push.
Problem Understanding
Reverse Integer: given a signed 32-bit integer x, return x with its digits reversed. If the reversed value falls outside [-2^31, 2^31 - 1], return 0. Assume you cannot store 64-bit integers.
Examples: 123 → 321, -123 → -321, 120 → 21.
The Intuition: Pop From One End, Push Onto the Other
Two arithmetic moves do the whole job:
- Pop the last digit of
x:digit = x % 10, thenx /= 10. - Push it onto the end of
result:result = result * 10 + digit.
Repeat until x is 0 and the digits come out reversed. The only hard part is the 64-bit ban: result * 10 can overflow before you get a chance to compare it. So compare first. INT_MAX is 2147483647, so if result is already above 214748364, or equal to it with a next digit above 7, the push would overflow. The same digit-at-a-time arithmetic underlies Pow(x, n), which reads the bits of n instead of decimal digits, and Plus One.
Interactive Walkthrough
The top row is what is left of x; the bottom row is result, with the digit just pushed highlighted. Try Overflow to see the check stop the run, and Just fits for a reverse that lands 6 below the limit.
Dry Run Table
Input: x = 120
| Step | digit | x after | result |
|---|---|---|---|
| 1 | 0 | 12 | 0 |
| 2 | 2 | 1 | 2 |
| 3 | 1 | 0 | 21 |
Answer: 21. The trailing zero is pushed first, while result is still 0, so it leaves no trace.
The Solution Template
Java, C++ and C check both bounds before the push. Python reverses the absolute value and restores the sign. JavaScript numbers are exact well past 2^31, so it can push first and compare after.
Reverse Integer Code
1var reverse = function(x) {2 const MAX = 2 ** 31 - 1, MIN = -(2 ** 31);3 let result = 0;4 while (x !== 0) {5 const digit = x % 10;6 x = Math.trunc(x / 10);7 result = result * 10 + digit;8 if (result > MAX || result < MIN) return 0;9 }10 return result;11};
Edge Cases & Common Mistakes
- Checking after the multiply: in C, C++ and Java,
result * 10has already overflowed (undefined behaviour in C and C++), so the check comes too late. - INT_MIN:
-2147483648has no positive counterpart; takingabsof it overflows in fixed-width languages, so keep the sign in each digit instead. - Trailing zeros:
120becomes21, not021. - Zero: the loop never runs and the answer is 0.
- Using a 64-bit long and comparing at the end: works in practice, but breaks the stated constraint.
Summary
Pop the last digit with % 10 and / 10, push it onto result with * 10 +, and check against INT_MAX / 10 and INT_MIN / 10 before every push. Return 0 on overflow. O(log |x|) time, O(1) space.
More practice: DSA interview questions with answers · patterns cheat sheet
