LeetCode 7. Reverse Integer

题目

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.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

分析

翻转整数

代码

1
2
3
4
5
6
7
8
9
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s = cmp(x, 0)
r = int(str(s*x)[::-1]) ## 负负得正
return s*r * (r < 2**31) ## 如果 r 大于 2**31 那么返回 0

点评

首先利用 str 来翻转,然后转成 int ,接着和 2**31(32位的整数最大值) 比较,如果小于,则返回 0