LeetCode Everyday:堅持價值投資,做時間的朋友!!!
題目:
給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
注意:假設我們的環境只能存儲得下 32 位的有符號整數,則其數值範圍爲。請根據這個假設,如果反轉後整數溢出那麼就返回 0。
示例:
- 示例1
輸入: 123 輸出: 321
- 示例2
輸入: -123 輸出: -321
- 示例3
輸入:120 輸出:21
代碼
方法一: 字符轉換
執行用時 :52 ms, 在所有 Python3 提交中擊敗了25.21%的用戶
內存消耗 :13.7 MB, 在所有 Python3 提交中擊敗了6.67%的用戶
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
strx = str(x)
x = int('-' + strx[1:][::-1]) if x<0 else int(strx[::-1])
return 0 if x<-2**31 or x>2**31-1 else x
"""
For Example: input: x = -123
output: -321
"""
x = -123
solution = Solution()
result = solution.reverse(x)
print('輸出爲:', result) # -321
方法二: 數學推算
執行用時 :32 ms, 在所有 Python3 提交中擊敗了98.25%的用戶
內存消耗 :13.5 MB, 在所有 Python3 提交中擊敗了6.67%的用戶
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag = -1 if x<0 else 1
x = abs(x)
res = 0
while x:
res = res*10 + x%10
x //= 10
res *= flag
return 0 if res<-2**31 or res>2**31-1 else res
"""
For Example: input: x = -123
output: -321
"""
x = -123
solution = Solution()
result = solution.reverse(x)
print('輸出爲:', result) # -321
參考
- https://www.bilibili.com/video/BV1tp411A7Eu?from=search&seid=13251925464525554525