7. Reverse Integer
2018-05-30 本文已影响0人
JERORO_
题目描述
Given a 32-bit signed integer, reverse digits of an integer.
思路
凑出符合要求的string,转成int后return
Detail
- 判断正负
- 从后往前loop,从第一个非0的数字开始,append到ans中
- 如果不为空,且在区间内,返回int(ans)
Complexity
Time: O(n)
Space: O(1)
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
INT_MAX = 2**31 -1
INT_MIN = -2**31
ans = ""
if x < 0:
ans += "-"
x = abs(x)
string = str(x)[::-1]
start = False
for i in string:
if i != "-" and i != "0":
start = True
if start:
ans += i
if ans == "" or int(ans) > INT_MAX or int(ans) < INT_MIN:
return 0
return int(ans)