給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
示例 1:
輸入: 123輸出: 321
示例 2:
輸入: -123輸出: -321
示例 3:
輸入: 120輸出: 21
注意:
假設我們的環境只能存儲得下 32 位的有符號整數,則其數值範圍爲 [−231, 231 − 1]。請根據這個假設,如果反轉後整數溢出那麼就返回 0。
class Solution: def reverse(self, x: int) -> int: if x > 0: xstr = str(x) if not xstr.endswith('0'): xlist = list(xstr) xlist.reverse() x = int(''.join(xlist)) else: xlist = list(xstr) xlist.pop() xlist.reverse() x = int(''.join(xlist)) if x > pow(2, 31): return 0 else: return x elif x == 0: return x else: x = x.__abs__() xstr = str(x) if not xstr.endswith('0'): xlist = list(xstr) xlist.reverse() x = int(''.join(xlist)) else: xlist = list(xstr) xlist.pop() xlist.reverse() x = int(''.join(xlist)) if x > pow(2, 31): return 0 else: return 0-x
執行用時 : 56 ms, 在Reverse Integer的Python3提交中擊敗了98.51% 的用戶
內存消耗 : 13.1 MB, 在Reverse Integer的Python3提交中擊敗了90.48% 的用戶