力扣 7. 整数反转python 每日一题

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入:x = 123
输出:321

示例 2:

输入:x = -123
输出:-321

示例 3:

输入:x = 120
输出:21

示例 4:

输入:x = 0
输出:0

提示:

  • -231 <= x <= 231 - 1
class Solution:
    def reverse(self, x: int) -> int:
        xlist=list(str(x))
        xl=len(xlist)
        rxlist=['']*xl
        if x==0:
            return 0
        for i in range(xl):
            if xlist[0]=="-" :
                if i==0:
                    rxlist[0]=xlist[0]
                else:
                   rxlist[i]= xlist[xl-i]
            else:
                rxlist[i]=xlist[xl-i-1]
        rx=int("".join(rxlist))
        if rx<-2**31 or rx >=2**31:
            return 0
        else:
            return rx
晚生不才,请多指教!
原文地址:https://www.cnblogs.com/lkc-test/p/14678715.html