1. 程式人生 > 其它 >整數取出每位數字_leetcode 7 整數反轉

整數取出每位數字_leetcode 7 整數反轉

技術標籤:整數取出每位數字

5511c4268e62ed33534158fc4739f499.png

給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。

示例 1:

輸入: 123
輸出: 321

示例 2:

輸入: -123
輸出: -321

示例 3:

輸入: 120
輸出: 21

注意:

假設我們的環境只能儲存得下 32 位的有符號整數,則其數值範圍為 [−231, 231 − 1]。請根據這個假設,如果反轉後整數溢位那麼就返回 0。

#
# @lc app=leetcode.cn id=7 lang=python3
#
# [7] 整數反轉
#

# @lc code=start
class Solution:
    def reverse(self, x: int) -> int:
        MAX = pow(2,31) - 1
        MIN = -pow(2,31)
        flag = 1 if x>0 else -1
        x=abs(x)
        num=0
        while(x):
            num=num*10+x%10
            x=x//10
        num*=flag
        num = 0 if num>MAX or num<MIN else num
        return num
# @lc code=end