IntReverse.py 1.15 KB
Newer Older
牛家玺 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        stark = []
        symbol = ""
        for c in str(x):
            if c != '-':
                stark.append(c)
            else:
                symbol = '-'

        value = ""
        if symbol != "":
            value = value + symbol

        while stark:
            value = value + stark.pop()

        rtype = int(value)
        if rtype > 2147483647 or rtype < -2147483648:
            return 0
        else:
            return rtype


i = 123
Solution().reverse(i)

i = -123
Solution().reverse(i)

i = 120
Solution().reverse(i)


class Solution1:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        max = 2147483647
        sign = 1 if x >= 0 else -1
        y = 0
        while True:
            a = x // 10
            b = x - a * 10
            y = b + y * 10
            x = a
            if y > max:
                return 0
            if x == 0:
                return sign * y


i = 123
print(Solution1().reverse(i))

i = -123
print(Solution1().reverse(i))

i = 120
print(Solution1().reverse(i))