Problem Description
You are given a signed 32-bit integer x.
Write a function reverse that takes x and returns the number with its digits reversed.
If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Constraints
xis in the range from-231to231 - 1
Examples
Input: x = 123
Answer: 321
Solution
Let's split the problem into two parts:
- Reversing a small number. For this we reuse the
reversefunction from the A number after a double reversal problem. - Handling a possible overflow of the 32-bit range.
32-bit overflow
As the problem states, the number cannot exceed the 32-bit range [-231, 231 - 1].
This means that if we try to reverse 2147483647, on the last iteration we get 7463847412, which is way out of bounds.
So how do we handle the overflow?
Let's call the upper bound of the 32-bit range MAX_INT and the lower bound MIN_INT.
Now let's state a few rules.
For positive numbers
- If
res > MAX_INT / 10, then after multiplying it by 10 and addingrightwe're guaranteed to overflow. - If
res == MAX_INT / 10, then after multiplying it by 10 and addingrightwe overflow only ifright > 7.
For negative numbers
- If
res < MIN_INT / 10, then after multiplying it by 10 and addingrightwe're guaranteed to overflow. - If
res == MIN_INT / 10, then after multiplying it by 10 and addingrightwe overflow only ifright < -8.
Implementation
Note that in TypeScript we have to round floating-point numbers depending on their sign. There are also no built-in constants for the minimum and maximum 32-bit integers, so we define them manually.
export const reverse = (x: number): number => {
const maxInt32 = Math.pow(2, 31) - 1;
const minInt32 = Math.pow(2, 31) * -1;
let left = x;
let res = 0;
while (left !== 0) {
const right = left % 10;
left = left > 0 ? Math.floor(left / 10) : Math.ceil(left / 10);
const max = Math.floor(maxInt32 / 10);
const min = Math.ceil(minInt32 / 10);
if (res > max || (res == max && right > 7)) {
return 0;
}
if (res < min || (res == min && right < -7)) {
return 0;
}
res = res * 10 + right;
}
return res;
};Complexity Analysis
Time Complexity
To reverse the number we perform k iterations, where k is the number of digits, which is roughly log(x).
So the complexity is O(log(x)).
Space Complexity
O(1): the additional memory is constant.