Given any number, elaborate a function that performs the sum of its digits using recursive python

Asked

Viewed 118 times

-1

Given any number, prepare a function that performs the sum of its digits using of recursion. So, for example, if the number 1435 is passed as parameter, the function developed should return the number 13 as a result in python

1 answer

1


Numbers are organized into classes and orders.

inserir a descrição da imagem aqui

To recursively sum the digits of a number one must find out which is the first class unit, to sum in totalizer and remove its digit from the number.

To find out which is the unit of a number just get the rest of a division by 10.

To remove the unit of a number round down the result of dividing that number by 10. Ref: math.floor()

import math

def somar_algarismos(numero, total=0):
  if numero == 0: return total #Se não tiver mais algarismos para somar retorna o total 

  unidade= numero % 10 # obtém o algarismarmo de primeira ordem da primeira classe
  novo_numero = math.floor(numero / 10) # obtém um número com unidade removida

  return somar_algarismos(novo_numero, total + unidade) #Recursivamente aplica a mesma operação ao novo número obtido com a sua antiga unidade já totalizada.


print(somar_algarismos(135711))

Code in Repl.it: https://repl.it/repls/InternalSereneMatch

  • 1

    You can also use numero // 10, which already returns the "rounded" value, without using floor: https://docs.python.org/3/glossary.html#term-floor-Division

  • Alternative solution (accepting negative numbers): https://ideone.com/9EMcip

  • @hkotsubo . I really like the python language, but things like that here makes me apprehensive.

  • 1

    https://stackoverflow.com/q/1907565

Browser other questions tagged

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