Python Reverse Integer Using Recursion
Solution 1:
This should work:
from math import log10
def rev(num):
if num < 10:
return num
else:
ones = num % 10
rest = num // 10
#print ones, rest, int(log10(rest) + 1), ones * 10 ** int(log10(rest) + 1)
return ones * 10 ** int(log10(rest) + 1) + rev(rest)
print rev(9000), rev(1234), rev(1234567890123456789)
You could also reduce the number of times you call log10
and number of math operations by using a nested recursive function:
defrev(num):
defrec(num, tens):
if num < 10:
return num
else:
return num % 10 * tens + rec(num // 10, tens // 10)
return rec(num, 10 ** int(log10(num)))
Solution 2:
It's running multiple times, but it only returns the left-most digit. It's pretty easy to see that's the case, if you consider under what circumstance the if
will be true.
To make this work, you need to add in the digits that you skipped as you pass out of the recursion. The following works by simply tacking the passed digits to the left of the previous result. I'd rather do it without the string conversion, but I couldn't come up with an elegant way to do that...
defreverseDisplay(number):
if number<10:
return number
else:
returnint(str(number%10) + str(reverseDisplay(number//10)))
defmain():
number=int(input("Enter a number:"))
print(number%10,end='')
print(reverseDisplay(number))
main()
Solution 3:
Edit: This is a working solution.
def rev(x,prod=0):if x <10:returnprod+ x
else:prod=prod*10+ x%10*10return rev(x /10,prod)
Result:
>>>rev(123)
321
>>>rev(12345)
54321
>>>rev(72823780029)
92008732827L
>>>rev(1)
1
Solution 4:
This should work : checked on Python3
# reverse a number
def reverseNum(n, rem=0):
if n == 0:
return (rem)//10else:
return reverseNum(n//10, (rem+(n%10))*10)print(reverseNum(7165))
print(reverseNum(123456789))
Little modified version:
def reverseNum(n, rem=0):
if n == 0:
return rem
elif n<10:
return reverseNum(n//10, (rem+(n%10)))else:
return reverseNum(n//10, (rem+(n%10))*10)
print(reverseNum(7165))
print(reverseNum(123456789))
Solution 5:
defreverseDisplay(number):
if number<10:
return number #1
first_digit = number % 10#2
the_rest = reverseDisplay(number//10)
ex = 0while1: #3
ex = ex + 1if number//(pow(10,ex)) == 0:
break
ex = ex - 1return first_digit*pow(10,ex) + the_rest #4
Here's how it works... (I've labelled the lines Im referring to here)
- line 1: exit condition. But you know this
- line 2: get the last digit. % means find the remainder of the division
- line 3: if say we pass in 123. At this point we have first_digit=3 and the_rest=21. We want the result to be 321 = 300 + 21. So pretty much what we need is to know how many times we need to times first_digit by 10 for this to work
- line 4: mmm delicious
Post a Comment for "Python Reverse Integer Using Recursion"