Leetcode练习(Python):数学类:第7题:整数反转:给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

题目:
整数反转:给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31,  2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

思路:

思路简单。

程序:

class Solution:
    def reverse(self, x: int) -> int:
        if -2**31 < x < 2**31 - 1:
            x = x
        else:
            return 0
        if abs(x) < 10:
            return x
        negative = 0
        if x < 0:
            x = -x
            negative = 1
        x = str(x)[::-1]
        while x[0] == '0':
            x = x[1:]
        x = int(x)
        if negative == 1:
            x = -x
        if -2**31 < x < 2**31 - 1:
            return x
        else:
            return 0
原文地址:https://www.cnblogs.com/zhuozige/p/12829771.html