7. Reverse Integer
Math ·Problem Statement
link: LeetCode.cn LeetCode Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Constraints:
-2^31 <= x <= 2^31 - 1
Example:
Input: x = 123
Output: 321
Input: x = -123
Output: -321
Input: x = 120
Output: 21
Constraints: -2^31 <= x <= 2^31 - 1
Solution Approach
The solution reverses the digits of the integer while handling edge cases such as negative numbers and overflow by continuously building the reversed number and checking if it exceeds the 32-bit integer range.
Algorithm
- Handling Negative Numbers: The solution accounts for negative integers by first converting the number to its positive form, reversing the digits, and then restoring the original sign.
- Overflow Protection: It checks for potential overflow conditions by ensuring that the reversed number does not exceed the 32-bit integer limits. If an overflow is detected, it returns 0.
- Digit Extraction and Reversal: The algorithm extracts digits from the integer using modulo and integer division operations, then builds the reversed number by multiplying the current reversed value by 10 and adding the extracted digit.
Complexity
time complexity: O(log n) space complexity: O(1)
Implement
class Solution:
def reverse(self, x: int) -> int:
isNegative = 1
MIN, MAX = -2 ** 31, 2 ** 31 - 1
if x < 0:
isNegative = -1
x = -x
v = 0
while x:
v = v * 10 + x % 10
x //= 10
if v > MAX:
return 0
return v * isNegative