简体   繁体   English

在 python 中反转整数不起作用

[英]Reversing an integer in python is not working

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

Why is this code not giving me the reverse of an integer in python?为什么这段代码没有给我 python 中整数的反转?

If you are using Python 3, use integer division // since / will give you a floating point number.如果您使用的是 Python 3,请使用整数除法//因为/会给您一个浮点数。

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

You can even improve you code by deleting the variable d before the while loop because its value is reassigned when you enter the loop, and you can also use the augmented assignment operator //= instead of n = n // 10 , so you could would be:您甚至可以通过在 while 循环之前删除变量 d 来改进您的代码,因为它的值在您进入循环时被重新分配,并且您还可以使用扩充赋值运算符//=而不是n = n // 10 ,因此您可以将会:

def intreverse(n):
    x = 0

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

    return x

If you are worried about overflow for a specific integer size you can check if the integer is within say a 32-bit range with a simple if statement [-2^(31), 2^(31) - 1]如果您担心特定整数大小的溢出,您可以使用简单的 if 语句 [-2^(31), 2^(31) - 1] 检查整数是否在 32 位范围内

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM