How to reverse an int in python?

Without converting the number to a string:

def reverse_number(n):
    r = 0
    while n > 0:
        r *= 10
        r += n % 10
        n /= 10
    return r

print(reverse_number(123))

You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?

def line(bottles, ending):
    return "{0} {1} {2}".format(bottles, 
                                plural("bottle", bottles), 
                                ending)

Which runs like:

>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'

Then pass the result to reverse:

>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'

This makes it much easier to test each part of the code separately and see what's going on when you put it all together.


Something like this?

>>> x = 123
>>> str(x)
'123'
>>> str(x)[::-1]
'321'

Tags:

Python

Reverse