Reverse Integer
Given a signed 32-bit integer x, return x with its digits reversed. The sign is preserved, so reversing a negative number stays negative.
If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1] (that is, [-2147483648, 2147483647]), return 0 instead.
Assume the environment does not allow you to store 64-bit integers — you must detect the overflow rather than rely on a wider type (though the reference solutions below use a wider accumulator where the language makes that the clean choice).
Input / output
- Input:
x: int - Output:
int— the reversed value, or0on overflow
Constraints
-2147483648 <= x <= 2147483647
Follow-up
Trailing zeros (as in 120 -> 21) disappear naturally. How would you detect overflow using only 32-bit arithmetic, by comparing against 2147483647 / 10 before each multiply-and-add step?
Examples
Example 1
Example 2
Example 3