python刷LeetCode 之 【reverse數字】
阿新 • • 發佈:2019-01-08
給定一個 32 位有符號整數,將整數中的數字進行反轉。
示例 1: 輸入: 123 輸出: 321
示例 2: 輸入: -123 輸出: -321
示例 3: 輸入: 120 輸出: 21
注意:
假設我們的環境只能儲存 32 位有符號整數,其數值範圍是 [−231, 231 − 1]。根據這個假設,如果反轉後的整數溢位,則返回 0。
class Solution:
def reverse(x):
"""
:type x: int
:rtype: int
"""
if x >= 0:
rNum = int(str(x)[::-1])
else:
rNum = int("-" + str(-x)[::-1])
# 判斷返回引數是否超出整數範圍
if rNum > (pow(2, 31) - 1) or rNum < pow(-2, 31):
return 0
else:
return rNum