[LeetCode]题解(python):007-Reverse Integer

时间:2023-02-02 22:44:06

题目来源:

https://leetcode.com/problems/reverse-integer/


题意分析:

这道题目很简单,就是将一个数反转,123变321,-123变321.


题目思路:

这题目很简单,先把数字求绝对值x,然后x%10取最后一位,然后ans = ans*10 + x%10,加上最后一位。然后x去掉最后一位。知道x = 0.要注意的时候,超出32位int类型的时候设置等于0就行了。


代码(python):

 class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
positive = True
if x < 0:
positive = False
x = abs(x)
ans = 0
while x > 0:
ans = ans * 10 + x % 10
x //= 10
if ans > 2147483647:
return 0
if not positive:
return -1*ans
return ans

转载请注明出处:http://www.cnblogs.com/chruny/p/4798828.html