【LeetCode每天一题】Reverse Integer(反转数字)

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:                               Input: 123                       Output: 321

Example 2:                               Input: -123                      Output: -321

Example 3:                               Input: 120                        Output: 21 

Note:  Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

思路:对于负数设置一个标志位,然后将其转化成正整数,再来计算,最后判断大小是否超过了[−231,  231 − 1]这个范围。时间复杂度为O(log 10 x), 空间复杂度为O(1)。

代码


 1 class Solution(object):
 2     def reverse(self, x):
 3         """
 4         :type x: int
 5         :rtype: int
 6         """
 7         if x == 0:                     # 为0直接返回
 8             return 0
 9         res, neg_flag = 0,False         # 设置结果和负数标志位
10         if x < 0:
11             neg_flag = True
12             x = abs(x)
13         while x:                      # 进行反转
14             tem = x % 10
15             x = x// 10
16             res = (res*10 + tem)  
17         if neg_flag:                   # 判断舒服标志位,并进行相应的转换
18             res =  0-res
19         if res > pow(2,31)-1 or res < -pow(2,31):      # 判断是否超出范围, 直接返回0
20             return 0
21         return res                  # 返回结果

猜你喜欢

转载自www.cnblogs.com/GoodRnne/p/10635519.html