I'm attempting to create a function that will sum all the digits
and will return the sum of the summarized number.
Example:
For Input getNumValue(1589)
The Output will be: 5
Becuase: 1 + 5 + 8 + 9 = 23
And 2 + 3 = 5
So the output will be 5
Because we can't split it into more digits.
I did managed to create a recursion function that summarize the digits:
def getNumValue(number: int):
if number == 0:
return 0
return (number % 10 + getNumValue(int(number / 10)))
But I can't seem to utilize it to my cause.
Btw
I don't want to use any strings
And I'm trying to use recursion so far no luck.
I bet this is a known mathematic problem I'm just unfamiliar with.
Any advice?
Even shorter:
def getNumValue(number: int): return ((number-1) % 9) + 1
The digit sum is always in the same remainder class mod 9 as the original decimal number, this applies recursively, and thus reducing it to one digit just is the remainder under division by 9.
The shift by 1
just serves the purpose that the remainder class 0
is represented by 9
.