Home > python > Reverse an integer

Reverse an integer

Exercise

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

Solution

#!/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.

Notes

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
About these ads
Categories: python Tags: , ,
  1. RrOo
    September 29, 2010 at 14:02 | #1

    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).

    #!/usr/bin/ruby
    	 
    def reverse_int( n )
        n.to_s.reverse.to_i
    end
    
    n = 83657
    puts n                   # 83657
    puts reverse_int( n )    # 75638
    
  1. No trackbacks yet.
You must be logged in to post a comment.
Follow

Get every new post delivered to your Inbox.

Join 61 other followers

%d bloggers like this: