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)。
代码
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x == : # 为0直接返回
return
res, neg_flag = ,False # 设置结果和负数标志位
if x < :
neg_flag = True
x = abs(x)
while x: # 进行反转
tem = x %
x = x//
res = (res* + tem)
if neg_flag: # 判断舒服标志位,并进行相应的转换
res = -res
if res > pow(,)- or res < -pow(,): # 判断是否超出范围, 直接返回0
return
return res # 返回结果