0
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?

5
  • 1
    What version of Python do you use? In Python-3, n/10 is floating-point division, not integer division. Commented Feb 7, 2017 at 5:03
  • What does it give you? Commented Feb 7, 2017 at 5:04
  • fyi: you can do this simply with int(str(n)[::-1]) Commented Feb 7, 2017 at 5:04
  • @JulienBernu For practical purposes, you can. For pedagogic, you cannot. But then, nobody would reverse an integer for any practical purpose. Commented Feb 7, 2017 at 5:05
  • @ArkaBhowmick, keep in mind that you should validate the answer if it was useful according to this Commented Feb 7, 2017 at 5:36

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

@ArkaBhowmick, please validate the answer if it was useful, keep in mind that that is the way stackoverflow works
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.