來源
https://leetcode-cn.com/problems/reverse-integer/description/
題目描述
給定一個 32 位有符號整數,將整數中的數字進行反轉。
示例 1:
輸入: 123
輸出: 321
示例 2:
輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:
假設我們的環境只能存儲 32 位有符號整數,其數值范圍是 [−2^31, 2^31 − 1]。根據這個假設,如果反轉后的整數溢出,則返回 0。
代碼實現
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x = int(str(x)[::-1]) if x >= 0 else - int(str(-x)[::-1])
return x if x < 2147483648 and x >= -2147483648 else 0