您的位置:首页 > 其它

(LeetCode)Reverse Integer --- 反转整数

2016-10-14 10:01 666 查看
Reverse digits of an integer.

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

click to show spoilers.

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.
Update (2014-11-10):

Test cases had been added to test the overflow behavior.

Subscribe to see which companies asked this question

解题分析:

注意读入和返回的数都是 int 型的,这时就要考虑反转后这个数会不会超 int,

超的话就返回 0 。这时处理数时最好用比 int 大的类型,不然恐怕会超范围。

当然也可以用 int :
if (result > (INT_MAX/10))


还有一点就是还要考虑前导零。

这里在python中有相应的函数来处理,比较方便。
# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
def reverse(self, x):
revx = int(str(abs(x))[::-1])
if revx > math.pow(2, 31):
return 0
else:
return revx * cmp(x, 0)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: