I was reviewing the topic of recursion in a tutorial site and came across the problem and solution below:
Problem:
Given an integer, create a function which returns the sum of all the individual digits in that integer. For example: if n = 4321, return 10 since 4+3+2+1=10.
Solution:
def sum_func(n):
if n<10:
return n
else:
return n%10 + sum_func(int(n/10))
pass
I understand the "if n<10" is the base case - if n is single digit, then just return n. What I couldn't wrap my head around is the "n%10 + sum_func(int(n/10))" line of code. Assume n is 235, n%10 will equal 5 and int(n/10) will equal 23. Then ultimately 5 + 23 will become 28 and not 10.
Could someone please help me understand what "n%10 + sum_func(int(n/10))" does? If you could walk through the logic one line at a time that would be greatly appreciated!
int(n/10)is 23, but you are not adding that. Instead, you are addingsum_func(int(n/10)), which is5(2+3).n%10gives last integer1, 2 3 4in this order. So try to get digits you need to slice n withint(n/10)this gives432, 43, 4so you got1+2+3+4=10