How to reverse an int in python?

Question:

I’m creating a python script which prints out the whole song of ’99 bottles of beer’, but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.

This is my full script,

def reverse(str):
   return str[::-1]

def plural(word, b):
    if b != 1:
        return word + 's'
    else:
        return word

def line(b, ending):
    print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)

for i in range(99, 0, -1):
    line(i, "of beer on the wall")
    line(i, "of beer"
    print reverse("Take one down, pass it around")
    line(i-1, "of beer on the wall n")

I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.

Asked By: Matthew C

||

Answers:

Something like this?

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

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.

Answered By: jonrsharpe

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))
Answered By: Alberto

You can cast an integer to string with str(i) and then use your reverse function.

The following line should do what you are looking for:

    def line(b, ending):
        print reverse(str(b)) or reverse('No more'), plural(reverse('bottle'),reverse(str(b))), reverse(ending)
Answered By: Amduscias

Original number is taken in a

a = 123

We convert the int to string ,then reverse it and again convert in int and store reversed number in b

b = int("".join(reversed(str(a))))

Print the values of a and b
print(a,b)

Answered By: Divyank

best way is

x=12345
a=str(x)[::-1]\ In this process i have create string of inverse of integer (a="54321")
a=int(a) \ Here i have converted string a in integer 

or
one line code is

a=int(str(x)[::-1]))
Answered By: Satyamskillz IN
def reverse_number(n):
r = 0
while n > 0:
    r *= 10
    r += n % 10
    n /= 10
return r

print(reverse_number(123))

This code will not work if the number ends with zeros, example 100 and 1000 return 1

Answered By: srujan kumar
def reverse_number(n):
    r = 0
    while n > 0:
        r = (r*10) + (n % 10)
        print(r)
        r *=10
        n //= 10
    return r


print(reverse_number(123))
Answered By: Vinay

I have written it in a different way, but it works

def isPalindrome(x: int) -> bool:

    if x<0:
        return False
    elif x<10:
        return True
    else:
        rev=0
        rem = x%10
        quot = x//10
        rev = rev*10+rem
        while (quot>=10):
           rem = quot%10
           quot = quot//10
           rev = rev*10+rem
        rev = rev*10+quot
        if rev==x:
            return True
        else:
            return False

res=isPalindrome(1221)
Answered By: Anuj shah
def reverse(num):
  rev = 0
  while(num != 0):
      reminder = num % 10
      rev = (rev * 10 ) + reminder
      num = num // 10 
  print ("Reverse number is  : " , rev )
 
num=input("enter number : ")
reverse(int(num))

#/ always results into float

#// division that results into whole number adjusted to the left in the number line

Answered By: passionatedevops

I think the following code should be good to reverse your positive integer.
You can use it as a function in your code.

  n = input()  # input is always taken as a string
  rev = int(str(n)[::-1]) 

If you are having n as integer then you need to specify it as str here as shown. This is the quickest way to reverse a positive integer

Answered By: Samit Saxena

Easily you can write this class:

class reverse_number:
            def __init__(self,rvs_num):
                self.rvs_num = rvs_num
                rvs_ed = int(str(rvs_num)[::-1])
                print(rvs_ed)

You can use it by writing:

reverse_number(your number)
Answered By: Sith fiLe
import math

def Function(inputt):

    a = 1
    input2 = inputt

    while(input2 > 9):

        input2 = input2/10
        a = a + 1

    print("There are ", a, " numbers ")
    N = 10  
    m = 1
    print(" THe reverse numbers are: ")

    for i in range(a):
        l = (inputt%N)/m
        print(math.floor(l), end = '')
        N = N*10
        m = m*10
    print(" n")
    return 0
enter = int(input("Enter the number: "))
print(Function(enter))
Answered By: Azamat
def reverse(x):
        re = 0
        negative = x < 0
        MAX_BIG = 2 ** 31 -1
        MIN_BIG = -2 ** 31 
        x = abs(x)

        while x != 0:
            a = int(x % 10)
            re = re * 10 + a
            x = int(x // 10)

        reverse = -1 * re if negative else re
        return 0 if reverse < MIN_BIG or reverse > MAX_BIG else reverse

this is for 32 – bit integer ( -2^31 ; 2^31-1 )

Answered By: Baxromov

More robust solution to handle negative numbers:

def reverse_integer(num):
    sign = [1,-1][num < 0]
    output = sign * int(str(abs(num))[::-1])
Answered By: Gunjan

An easy and fast way to do it is as follows:

    def reverse(x: int|str) -> int:
        reverse_x = int(''.join([dgt for dgt in reversed(num:=str(x)) if dgt != '-']))
        if '-' in num:
            reverse_x = -reverse_x'
        return reverse_x

First we create a list (using list comprehension) of the digits in reverse order. However, we must exclude the sign (otherwise the number would turn out like [3, 2, 1, -]). We now turn the list into a string using the ”.join() method.

Next we check if the original number had a negative sign in it. If it did, we would add a negative sign to reverse_x.

Answered By: Jason Grace
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.