简体   繁体   中英

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?

If you are using Python 3, use integer division // since / will give you a floating point number.

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:

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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