Integer Reversal with Overflow Detection
This challenge asks you to reverse the digits of a given 32-bit signed integer. Integer reversal is a fundamental operation in computer science, often used in algorithms dealing with number properties, data manipulation, or even some cryptographic functions. Mastering it helps in understanding basic arithmetic operations on numbers and handling edge cases like negative signs and numerical limits.
Problem Description
Your task is to implement a function that takes a single 32-bit signed integer x as input and returns its digits reversed.
Key Requirements:
- Digit Reversal: The order of the digits must be reversed. For example, 123 should become 321.
- Sign Handling: If the input integer is negative, the reversed integer should also be negative. For example, -123 should become -321.
- Trailing Zeros: Trailing zeros in the original number become leading zeros in the reversed number and should be dropped. For example, 120 should become 21.
- Overflow Detection: The problem specifies that the environment can only store 32-bit signed integers, meaning the range
[-2^31, 2^31 - 1]. If reversingxcauses the value to go outside this range, the function must return 0. This check is crucial and must be handled correctly.
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, and the negative sign is preserved, resulting in -321.
Example 3:
Input: 1534236469
Output: 0
Explanation: The reversed integer would be 9646324351. This value is larger than the maximum 32-bit signed integer (2,147,483,647). Therefore, according to the problem's requirements, the function should return 0.
Constraints
xis a 32-bit signed integer, meaningxis in the range[-2^31, 2^31 - 1].- The function must return an integer.
- No specific time or space complexity is required, but an efficient solution is expected.
Notes
- Consider how you can extract the last digit of a number using the modulo operator (
%) and remove the last digit using integer division (/). - Pay close attention to how you can build the reversed number digit by digit.
- The most challenging aspect is detecting integer overflow before it occurs. Think about how you can check if adding a new digit or multiplying by 10 would push the
reversedvalue beyond the 32-bit integer limits (minimum(-2^31)and maximum(2^31 - 1)). It's generally safer to perform this check before the operation that might cause overflow. - Remember that
0reversed is0.