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
Constraints:
-231 <= x <= 231 - 1
Table of Contents
Solution
# Runtime: 40 ms, faster than 99.95% of Python3 online submissions for Reverse Integer.
# Memory Usage: 13.2 MB, less than 5.71% of Python3 online submissions for Reverse Integer.
class Solution:
def reverse(self, x: int) -> int:
if x > 0: # handle positive numbers
a = int(str(x)[::-1])
if x <=0: # handle negative numbers
a = -1 * int(str(x*-1)[::-1])
# handle 32 bit overflow
mina = -2**31
maxa = 2**31 - 1
if a not in range(mina, maxa):
return 0
else:
return a```
# Runtime: 40 ms, faster than 99.95% of Python3 online submissions for Reverse Integer.
# Memory Usage: 13.2 MB, less than 5.71% of Python3 online submissions for Reverse Integer.
class Solution:
def reverse(self, x: int) -> int:
if x > 0: # handle positive numbers
a = int(str(x)[::-1])
if x <=0: # handle negative numbers
a = -1 * int(str(x*-1)[::-1])
# handle 32 bit overflow
mina = -2**31
maxa = 2**31 - 1
if a not in range(mina, maxa):
return 0
else:
return a```