您的位置:首页 > 编程语言 > Python开发

[Leetcode]Reverse Integer

2015-02-04 14:21 411 查看
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
反转数字~有很多细节都要注意,例如负数问题,还有整数越界问题~虽然python不用处理整数溢出的问题,但在这题里如果不处理的话不能AC,所以在结尾判断了一下res是否大于2的31次方,如果大于的话就返回0
class Solution:
# @return an integer
def reverse(self, x):
res, num, sign = 0, abs(x), -1 if x < 0 else 1
while num:
num, res = num // 10, res * 10+ num % 10
return 0 if res > pow(2, 31) else res * sign
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python