您的位置:首页 > 其它

LeetCode Reverse Integer

2015-12-15 16:53 288 查看

LeetCode解题之Reverse Integer

原题

翻转一个intger类型的数字。

注意点:

有正负两种情况

integer是32位整型,考虑溢出

注意末尾有0的情况不能直接当作字符串翻转

例子:

输入: x=123

输出: 321

输入: x=-123

输出: -321

解题思路

由于Python可以支持几乎无限大的数,直接把末尾的数不断添加到目标书中即可。最后再处理溢出的情况。如果想通过转换为字符然后翻转的方法来实现,需要把末尾的0先去掉。

AC源码

class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
# Consider positive and negative situation
flag = 0
if x < 0:
flag = -1
else:
flag = 1
x *= flag
result = 0
while x:
result = result * 10 + x % 10
x /= 10
if result > 2147483647:
return 0
else:
return result * flag

if __name__ == "__main__":
assert Solution().reverse(321000) == 123
assert Solution().reverse(-321) == -123
assert Solution().reverse(1534236469) == 0


欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 算法