[Leetcode] 7. 反转整数 Python3

 

 依然是将给的整数转换为list,通过不断在li[0]位置插入元素实现反转。

 正负号的问题比较简单,取绝对值进行上述操作,当x小于0时,result取负;否则,返回result。

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        y = abs(x)  #取绝对值
        l = len(str(y)) 
        li = []
        r = l - 1      
        for i in range(l): 
            element = (y//(10**(r-i))) % 10  #数转化为list
            li.insert(0,element)
        #将li转换回数
        result = 0
        for j in range(l):
            result += li[j] * (10**(r-j))
        if x < 0:  #如果x小于0
            result = (-1) * result
        if -2147483648 < result < 2147483647:  #整数不溢出
            return result
        else:  #溢出
            return 0

猜你喜欢

转载自blog.csdn.net/niceHou666/article/details/81280936