Recursive function in python to invert a number

0

I need to do a recursive function in python to return the number of the inverted form, but to be converted to string.

I just managed to do it this 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 that I could do just using whole division and rest. Does anyone help?

    
asked by anonymous 30.09.2018 / 05:14

1 answer

1

A simple solution, but a rather boring logic to solve. Here is a way to solve this using integer division and recursion, without the conversion 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 to have helped, any further questions feel free to contact.

    
01.10.2018 / 07:48