在python中反转一个整数不起作用

时间:2017-02-07 05:00:30

标签: python integer reverse

def intreverse(n):   #reverse an integer
    x=0
    d=0
    while(n>0):
        d=n%10
        x=x*10+d
        n=n/10
    return (x)

//为什么这段代码在python中没有给我一个整数的反转?

2 个答案:

答案 0 :(得分:3)

如果您使用的是Python 3,请使用整数除法//,因为/将为您提供浮点数。

def intreverse(n):
    x=0
    d=0
    while n > 0:
        d = n % 10
        x= x * 10 + d
        n = n // 10
    return (x)

您甚至可以通过删除while循环之前的变量d来改进代码,因为当您进入循环时它的值会被重新分配,您还可以使用扩充赋值运算符//=而不是n = n // 10 ,所以你可能会:

def intreverse(n):
    x = 0

    while n > 0:
        d = n % 10
        x = x * 10 + d
        n //= 10

    return x

答案 1 :(得分:0)

如果您担心特定整数大小的溢出,可以使用简单的if语句[-2 ^(31),2 ^(31)-1]检查该整数是否在32位范围内。 / p>

def intreverse(self, x: int) -> int:
    negative = False
    if x < 0:
        negative = True
        x = x * -1

    res = 0
    while x != 0:
        res = (res * 10) + x % 10
        x = x // 10

        if (res > (2 ** 31) - 1) or (res < -(2 ** 31)):
            return 0

    return (res * -1) if negative else res