Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
自己的解法:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag=True
if x<0:
flag=False
if x==0:
return 0
x=abs(x)
arr=[]
while x>0:
arr.append(x%10)
x=x//10
res=0
for i in range(0,len(arr)):
res=res*10+arr[i]
if res> 2147483648 :
return 0
if flag:
return res
else:
return -res
一开始忽略了整数的范围,没有通过,后加上限制即可。
别人的解法,参考Reverse Integer:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
result = ((x>0)-(x<0)) * int(str(abs(x))[::-1])
return result if result >= -2 ** 31 and result < 2 ** 31 else 0
利用
int(str(abs(x))[::-1]) 取出数字的倒序
利用
((x > 0) - (x < 0))取出数字的正负号