欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

7. Reverse Integer

程序员文章站 2022-07-15 14:39:05
...

题目

7. Reverse Integer

我的代码

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        sign=False
        if x<0:
            sign =True
            x=-x
        li=[]
        while x>0:
            li.append(x%10)
            x/=10
        base=1
        result=0
        for i in range(len(li)-1,-1,-1):
            result+=base*li[i]
            base*=10
        if result>2**31-1:
            return 0
        if sign:
            return -result
        else:
            return result

优秀代码

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        int_max = 2**31
        reverse = 0
        flag = 0
        if x<0 :
            x = abs(x)
            flag = 1
        while x != 0:    
            digit = x%10
            reverse = reverse*10 + digit
            x = x // 10
        if (reverse > int_max):
            return 0
        if flag == 1:
            reverse = reverse*(-1)
        return reverse
相关标签: python leetcode