您的位置:首页 > 其它

Leetcode(7)——Reverse Integer

2016-03-04 13:49 411 查看
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

我的代码:

import math
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x1 = abs(x)
if x==0:
flag=0
else:
flag=x1/x
str=[]
while x1!=0:
ys=x1%10
str.append(ys)
x1=(x1-ys)/10
L=len(str)
x1=0
ind=0
while ind<len(str):
x1=x1+str[ind]*(10**(len(str)-ind-1))
ind=ind+1
if x1<2**31:
return x1*flag
else:
return 0

这里要注意一点的是,题目有提示注意溢出问题,假设输入的是一个32-bit整数,那么输出的数有可能会溢出(大于2^31),溢出的话我们就设为0。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: