Given a 32-bit signed integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1]
, then return 0
.
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Constraints:
-2^31 <= x <= 2^31 - 1
0
?
0
is a valid input and the output should be 0
.0
in any case where the result goes beyond the 32-bit signed integer range?
0
.0
.Let’s implement the proposed solution:
def reverse(x: int) -> int:
# Check the sign of the integer
sign = -1 if x < 0 else 1
# Convert to string, strip the sign, reverse the string, and convert back to integer
reversed_int = int(str(abs(x))[::-1])
# Apply the original sign
reversed_int *= sign
# Check for 32-bit signed integer overflow
if reversed_int < -2**31 or reversed_int > 2**31 - 1:
return 0
return reversed_int
# Test cases
print(reverse(123)) # Expected output: 321
print(reverse(-123)) # Expected output: -321
print(reverse(120)) # Expected output: 21
print(reverse(0)) # Expected output: 0
print(reverse(1534236469)) # Expected output: 0 (since reversed value overflows)
x
.x
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?