1. 程式人生 > >LeetCode 7 反轉整數 python

LeetCode 7 反轉整數 python

給定一個 32 位有符號整數,將整數中的數字進行反轉。
示例 1:
輸入: 123
輸出: 321
示例 2:
輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:
假設我們的環境只能儲存 32 位有符號整數,其數值範圍是 [−231, 231 − 1]。根據這個假設,如果反轉後的整數溢位,則返回 0。

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        s = str(x)
        st = list(s)
        if st[0]=='-':
            temp = st[1:]
            temp.reverse()
            st = ['-']+temp
        else:
            st.reverse()
        for item in st:
            if item == '0':
                st = st[1:]
            else:
                break
        if st:
            result = int(''.join(st))
            if result >= -2**31 and result <= 2**31-1:
                return result
            else:
                return 0
        else:
            return 0