Reverse Integer
Difficulty: Medium
Given a signed 32-bit integer, reverse its decimal digits and keep its sign.
If the result doesn't fit in a signed 32-bit integer (-2^31 to 2^31 - 1, the range of a 32-bit int in many languages), return 0.
Examples
Input: x = 123
Output: 321
Input: x = -123
Output: -321
The digits reverse the same way; the sign is kept as-is.
Input: x = 1534236469
Output: 0
Reversed, this would be 9646324351, which is larger than the maximum signed 32-bit value (2147483647) - so 0 is returned instead.
Constraints
-2^31 <= x <= 2^31 - 1
Approach
The direct way converts the number to a string (tracking the sign separately), reverses it, parses it back, and checks the 32-bit range.
The careful way uses only arithmetic. Take x's last digit with % 10, remove it with integer division by 10, and build the reversed result one digit at a time.
The key detail is overflow. Before each multiply-and-add step, check whether the next digit would push the result past the maximum or minimum. If so, return 0 right away.
Solutions
Brute Force - Reverse via String Conversion
Convert |x| to a string, reverse it, parse it back, and reapply the sign. Then check that the result fits the signed 32-bit range.
function reverse(x) {
const sign = x < 0 ? -1 : 1;
const reversed = Math.abs(x).toString().split("").reverse().join("");
const result = sign * Number(reversed);
const INT_MAX = 2 ** 31 - 1;
const INT_MIN = -(2 ** 31);
if (result > INT_MAX || result < INT_MIN) return 0;
return result;
}Time: O(d), where d is the number of digits in x · Space: O(d), for the string representation
Optimal - Build the Reversed Number Digit by Digit, Checking Overflow Early
Take digits off x with % 10 and integer division by 10, and build the reversed result. Before adding each digit, check whether it would push the result past the signed 32-bit range, and return 0 if so, before any overflow happens.
function reverse(x) {
const INT_MAX = 2 ** 31 - 1;
const INT_MIN = -(2 ** 31);
let result = 0;
while (x !== 0) {
const digit = x % 10; // keeps the sign of x automatically in JS
x = Math.trunc(x / 10);
if (
result > Math.trunc(INT_MAX / 10) ||
(result === Math.trunc(INT_MAX / 10) && digit > 7)
) {
return 0;
}
if (
result < Math.trunc(INT_MIN / 10) ||
(result === Math.trunc(INT_MIN / 10) && digit < -8)
) {
return 0;
}
result = result * 10 + digit;
}
return result;
}Time: O(d), where d is the number of digits in x · Space: O(1)