题目链接
https://leetcode.com/problems/reverse-integer/
题目原文
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
题目翻译
反转整数中的数字。
例子1:给定x=123,返回321;例子2:给定x=-123,返回-321。
本题的几个坑:
1. 原整数是以0结尾的,该如何处理?——比如x=10或x=100,那么都返回1。
2. 原整数反转后溢出怎么办?——比如x=1000000003,反转溢出,那么规定溢出的结果都返回0。
思路方法
这里Python处理整数不会主动溢出实际上会给解题带来麻烦,需要特殊处理。
思路一
循环通过对10取模得到尾部数字,一步步乘10构造新的翻转后的整数即可。然而要注意首先判断原数字的正负,最后还要判断结果是否溢出。
代码
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag = 1 if x >= 0 else -1
new_x, x = 0, abs(x)
while x:
new_x = 10 * new_x + x % 10
x /= 10
new_x = flag * new_x
return new_x if new_x < 2147483648 and new_x >= -2147483648 else 0
思路二
利用Python的字符串反转操作来实现对整数的反转,反转后的字符串要重新转换为整数。同上面一样,要注意正负和溢出情况。
代码
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x = int(str(x)[::-1]) if x >= 0 else - int(str(-x)[::-1])
return x if x < 2147483648 and x >= -2147483648 else 0
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/52039990