Problem Description
Given a signed 32-bit integer x, the task is to reverse its digits. If the reversed integer goes outside the 32-bit signed integer range [-2^31, 2^31 - 1], return 0. Note that the environment does not allow storing 64-bit integers.
Key Insights
- The problem requires reversing the digits while preserving the sign.
- Watch out for integer overflow due to the reversed number exceeding the 32-bit signed integer limits.
- The approach involves repeatedly extracting the last digit from the number and appending it to a new reversed integer.
- Overflow checks are done during each iteration before actually appending the digit.
Space and Time Complexity
Time Complexity: O(n), where n is the number of digits in the integer. Space Complexity: O(1), only constant extra space is used.
Solution
The solution uses a while loop to extract the last digit from the original number using modulo operation (x % 10) and then removes this digit using integer division (x //= 10). A reversed number is constructed by multiplying the current reversed number by 10 and adding the extracted digit. Before appending each digit, the algorithm checks if the new reversed number will overflow a 32-bit signed integer by comparing it with the thresholds derived from INT_MAX and INT_MIN. The algorithm handles negative values by working with x directly since the modulo and division operations work properly with negatives in most languages.