給定一個 32 位有符號整數(shù),將整數(shù)中的數(shù)字進(jìn)行反轉(zhuǎn)。
示例 1:
輸入: 123
輸出: 321
示例 2:
輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:
假設(shè)我們的環(huán)境只能存儲 32 位有符號整數(shù),其數(shù)值范圍是 [?2^31, 2^31 ? 1]。根據(jù)這個假設(shè),如果反轉(zhuǎn)后的整數(shù)溢出,則返回 0。
解答:
這道題我們可以把int轉(zhuǎn)換成str在進(jìn)行切片操作,非常簡單。只需要在判斷一下數(shù)字的范圍即可。
class Solution:
"""
:type x: int
:rtype: int
"""
def reverse(self, x):
if x >0:
x = int(str(x)[::-1])
else:
x=-int(str(-x)[::-1])
return x if x < 2147483648 and x >-2147483648 else 0