原題:給出一個 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
"""
stauts = -1 if x < 0 else 1
x = abs(x)
result =0
while x!=0:
result= result*10+x%10
x=x//10
if result > 2**31:
result =0
return result*stauts
另一種思路:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
tag = 1 if x >= 0 else -1 # 判斷在正負
st = str(abs(x)) # 取絕對值,且轉爲string
st = ''.join(re.findall('(.*)0*', st)) # 剔除尾部的0
res = int(st[::-1]) # 字符串轉爲int類型
res = res if res >= - 2147483648 and res <= 2147483647 else 0
return res * tag