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

 

题目来源:

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):

 1 class Solution(object):
 2     def reverse(self, x):
 3         """
 4         :type x: int
 5         :rtype: int
 6         """
 7         positive = True
 8         if x < 0:
 9             positive = False
10         x = abs(x)
11         ans = 0
12         while x > 0:
13             ans = ans * 10 + x % 10
14             x //= 10
15         if ans > 2147483647:
16             return 0
17         if not positive:
18             return -1*ans
19         return ans
View Code

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

原文地址:https://www.cnblogs.com/chruny/p/4798828.html