Recursive function in python to invert a number

Asked

Viewed 1,280 times

0

I need to do a recursive function in python to return the number the reverse way, but be convert to string.

I could only do it that way:

import math

def inverte(num):
 if(num < 10):
   return num

  q=num//10
  q=inverte(q)

  r=num%10
  inv=r*10**((math.floor(math.log10(q)+1)))+q

  return inv

 print(inverte(1234))

However, my teacher said I could do just using whole division and rest. Someone helps?

1 answer

1

A simple solution, but a rather boring logic to solve. Here’s a way to solve this using whole division and recursion, without converting to other types:

def inverte(num, aux=0):
    if num < 10:
        return aux + num
    aux = aux * 10 + num % 10 * 10
    return inverte(num // 10, aux)

In Python, the operator // functions as a floor Division (or entire division, as mentioned by your teacher).

I hope I’ve helped, any other questions feel free to contact.

  • In fact it can only have one parameter that function. That would be only the number. That way you did I already had thinking, but can only have a parameter in the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.