Reverse Integer
Given a signed 32-bit integer, reverse its digits. This is a common problem that tests your understanding of number manipulation and handling potential overflow conditions. Successfully reversing an integer requires careful consideration of both positive and negative numbers, as well as ensuring the result stays within the 32-bit signed integer range.
Problem Description
Your task is to write a function that takes a signed 32-bit integer as input and returns the integer with its digits reversed.
Key Requirements:
- Reverse the digits of the input integer.
- Preserve the sign of the original integer.
- Handle potential integer overflow. If the reversed integer exceeds the range of a signed 32-bit integer ([-2<sup>31</sup>, 2<sup>31</sup> - 1]), return 0.
Expected Behavior:
- Positive numbers should have their digits reversed.
- Negative numbers should have their digits reversed, with the negative sign maintained.
- Numbers ending in zero should have leading zeros removed after reversal (e.g., reversing 120 should result in 21, not 021).
Edge Cases to Consider:
- Zero (0)
- Single-digit numbers
- Numbers that, when reversed, will overflow the 32-bit signed integer range.
Examples
Example 1:
Input: 123
Output: 321
Explanation: The digits of 123 are reversed to form 321.
Example 2:
Input: -123
Output: -321
Explanation: The digits of -123 are reversed to form -321. The negative sign is preserved.
Example 3:
Input: 120
Output: 21
Explanation: The digits of 120 are reversed. The trailing zero becomes a leading zero, which is then removed, resulting in 21.
Example 4: (Overflow Case)
Input: 1534236469
Output: 0
Explanation: Reversing 1534236469 results in 9646324351. This value exceeds the maximum value for a signed 32-bit integer (2<sup>31</sup> - 1), so the function should return 0.
Example 5: (Overflow Case)
Input: -2147483648
Output: 0
Explanation: Reversing -2147483648 would result in -8463847412. This value is less than the minimum value for a signed 32-bit integer (-2<sup>31</sup>), so the function should return 0.
Constraints
- The input is a signed 32-bit integer.
- The range of a signed 32-bit integer is [-2<sup>31</sup>, 2<sup>31</sup> - 1].
- Your solution's time complexity should be efficient, ideally O(log n), where n is the absolute value of the input integer.
Notes
- You cannot use any 64-bit integer types to store the intermediate or final results.
- Think about how you can extract digits from a number and how you can build a new number from these extracted digits.
- The most critical part of this challenge is handling the potential for overflow. Carefully check your calculations at each step to ensure you don't exceed the 32-bit integer limits.