首页 > 编程语言 > 详细

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

时间:2015-09-10 19:14:24      阅读:148      评论:0      收藏:0      [点我收藏+]

 

题目来源:

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

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

原文:http://www.cnblogs.com/chruny/p/4798828.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!