Arka
Arka

Reputation: 75

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?

Upvotes: 0

Views: 470

Answers (2)

Steve Freed
Steve Freed

Reputation: 91

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

Upvotes: 0

lmiguelvargasf
lmiguelvargasf

Reputation: 69983

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

Upvotes: 3

Related Questions