最近再刷leetcode,除了鏈表之外的都用python 實(shí)現(xiàn),貼出一些代碼,希望指正.
問題描述:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
結(jié)題思路:
先判斷正負(fù)數(shù),然后去絕對(duì)值判斷位數(shù).
然后從高到底取每一位,存入list,
對(duì)于123
先 123/100 = 1
然后 23/10 = 2
然后 3/1 = 3
的方式得到每一位,再?gòu)男卤闅v求和.
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
b = len(str(x))
def revre(x):
list1 = []
x = abs(x)
if x>pow(2,31):
return 0
for i in range(b):
tmp = x // (pow(10, i))
list1.append(tmp % 10)
sum = 0
for i in range(b):
sum = sum + list1[i] * pow(10, (b - 1 - i))
if sum>pow(2,31):
return 0
return sum
if x > 0:
return revre(x)
else:
b = b-1
return -revre(x)
solution = Solution()
print(solution.reverse(1563847412))