Medium
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).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
-231 <= x <= 231 - 1
Here are the steps to solve the “Reverse Integer” problem:
x
is 0, return 0.x
(positive or negative).x
is negative, update the sign and make x
positive for the reversal process.x
to a string.x
was negative, apply the negative sign to the reversed integer.[-231, 231 - 1]
.class Solution:
def reverse(self, x: int) -> int:
# Handle special case for 0
if x == 0:
return 0
# Determine sign
sign = 1 if x > 0 else -1
# Make x positive for the reversal process
x = abs(x)
# Reverse the digits
reversed_str = str(x)[::-1]
# Remove leading zeros
reversed_str = reversed_str.lstrip('0')
# Convert back to integer
reversed_int = int(reversed_str)
# Apply sign
reversed_int *= sign
# Check for overflow
if reversed_int < -2**31 or reversed_int > 2**31 - 1:
return 0
# Return the reversed integer
return reversed_int
# Example Usage:
solution = Solution()
# Example 1:
x1 = 123
print(solution.reverse(x1)) # Output: 321
# Example 2:
x2 = -123
print(solution.reverse(x2)) # Output: -321
# Example 3:
x3 = 120
print(solution.reverse(x3)) # Output: 21
# Example 4:
x4 = 0
print(solution.reverse(x4)) # Output: 0
This code defines a Solution
class with a method reverse
that takes an integer x
as input and returns the reversed integer. The example usage demonstrates how to create an instance of the Solution
class and call the reverse
method with different inputs.