Home > python > Reverse an integer

Reverse an integer


Take an integer and reverse its digits. The result is also an integer. Example: 83657 becomes 75638.


#!/usr/bin/env python

def reverse_int(n):
    return int(str(n)[::-1])

n = 83657
print n                 # 83657
print reverse_int(n)    # 75638

Summary: convert the number to string, reverse the string, then convert it back to integer. Details: 83657 -> str(83657) returns "83657" which is a string -> reverse it, we get "75638" -> int("75638") converts it to an integer.


If you want to concatenate a string and an integer, first you need to convert the integer to string. Example:

n = 83657
print "The value of n is " + n          # error, won't work
print "The value of n is " + str(n)     # OK
Categories: python Tags: , ,
  1. RrOo
    September 29, 2010 at 14:02

    Here is my Ruby solution which is very similar but I think it is more OO like than your Python solution. Could we do the same in Python ? (I mean OO like code).

    def reverse_int( n )
    n = 83657
    puts n                   # 83657
    puts reverse_int( n )    # 75638
  2. September 4, 2018 at 13:55

    I think we can also use this code( This will be use to reverse a string as well number):

    a=str(input("enter a number:"))
    for c in range(b,0,-1):
  3. Raj Aryan
    October 5, 2018 at 20:12

    Simple and sweet:-

    def reverse_int(n):
      ans = 0
      while n > 0:
        (d,n) = (n%10,n//10)
        ans = 10*ans + d
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: