Leetcodeleetcode

7. Reverse Integer

2017-10-26  本文已影响3人  ciantian

最近再刷leetcode,除了链表之外的都用python 实现,贴出一些代码,希望指正.

问题描述:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

结题思路:

先判断正负数,然后去绝对值判断位数.
然后从高到底取每一位,存入list,
对于123
先 123/100 = 1
然后 23/10 = 2
然后 3/1 = 3
的方式得到每一位,再从新遍历求和.

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        b = len(str(x))

        def revre(x):
            list1 = []
            x = abs(x)
            if x>pow(2,31):
                return 0
            for i in range(b):
                tmp = x // (pow(10, i))
                list1.append(tmp % 10)
            sum = 0
            for i in range(b):
                sum = sum + list1[i] * pow(10, (b - 1 - i))
            if sum>pow(2,31):
                return 0
            return sum
        if x > 0:
            return revre(x)
        else:
            b = b-1
            return -revre(x)
solution = Solution()
print(solution.reverse(1563847412))
上一篇下一篇

猜你喜欢

热点阅读