Reverse Integer
Difficulty: Medium · Pattern: Bit Manipulation · LeetCode #7
Reverse the digits of a signed 32-bit integer x. If the reversed value falls outside [−2³¹, 2³¹ − 1], return 0. Assume the environment can't store 64-bit integers.
Examples
text
123 → 321
-123 → -321
120 → 21
1534236469 → 0 (9646324351 overflows)Hints
- Pop the last digit with
x % 10, push it withr = r * 10 + d. - Check for overflow before the push:
r > (2³¹ − 1) // 10meansr * 10would overflow.
Approach
Work with |x| and restore the sign at the end. Before each push, if r > 214748364 (or r == 214748364 and the digit > 7), the result would overflow, so return 0.
Pitfalls by language:
- Python's
%with negative numbers follows floor division (-123 % 10 == 7), so useabs. - JavaScript has no integer division. Use
Math.trunc(x / 10).
Complexity
Time: O(log₁₀ x). Space: O(1).
Python solution
def reverse(x):
LIMIT = 2 ** 31 - 1
sign = -1 if x < 0 else 1
x, r = abs(x), 0
while x:
d = x % 10
x //= 10
if r > (LIMIT - d) // 10:
return 0
r = r * 10 + d
return sign * rJavaScript solution
function reverse(x) {
const LIMIT = 2 ** 31 - 1, sign = x < 0 ? -1 : 1;
let a = Math.abs(x), r = 0;
while (a) {
const d = a % 10;
a = Math.trunc(a / 10);
if (r > (LIMIT - d) / 10) return 0;
r = r * 10 + d;
}
return sign * r;
}