Reverse Integer
MediumBit Manipulation
Given a signed 32-bit integer x, return the integer formed by reversing its decimal digits, keeping the original sign. Leading zeros in the reversed number are dropped (so 120 becomes 21).
If the reversed value falls outside the signed 32-bit range [-2^31, 2^31 - 1], return 0.
Python integers never overflow, but solve it as if your environment could only hold 32-bit signed integers: detect overflow before it would happen rather than building a large number and checking at the end.
Example 1
- Input:
- x = -120
- Output:
- -21
- Explanation
- Ignoring the sign, 120 reversed is 021, which is just 21. The sign is kept, so the answer is -21.
Example 2
- Input:
- x = 1463847412
- Output:
- 2147483641
- Explanation
- The digits reversed are 2147483641, which is still within the 32-bit maximum of 2147483647, so it is returned as is.
Example 3
- Input:
- x = 1534236469
- Output:
- 0
- Explanation
- The digits reversed are 9646324351, which is larger than 2147483647, so the answer is 0.
Constraints
-2^31 <= x <= 2^31 - 1