描述
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
Note:
-2^31 <= x <= 2^31 - 1
解析
根据题意,就是找出将 x 的每一个数字逆序排列,且正负相同的数字,且转换之后的数字在 [-2^31, 2^31 - 1] 之间,且不以 0 为前置的字符串,否则为 ‘0’ 。
解答
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
r = '0'
if x == 0:
return r
if x > 0:
r = str(x)[::-1].lstrip("0")
else:
r = "-" + str(abs(x))[::-1].lstrip("0")
if -(2 ** 31) > int(r) or int(r) > (2 ** 31) - 1:
return '0'
return r
运行结果
Runtime: 12 ms, faster than 97.90% of Python online submissions for Reverse Integer.
Memory Usage: 13.5 MB, less than 33.78% of Python online submissions for Reverse Integer.
原题链接:https://leetcode.com/problems/reverse-integer/
您的支持是我最大的动力