Reputation: 875
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!
Upvotes: 0
Views: 151
Reputation: 4646
if n = 235
then int(n/10)
is 23
. However, you do not add 5 and 23. You add sum_func(int(n/10))
and 5
.
sum_func(int(n/10))
is not int(n/10)
sum_func(int(n/10))
adds the digits in the number "23
" together.
As such, sum_func(int(n/10)) == 2 + 3 == 5
sum_func(235) == sum_func(235)
== sum_func(23) + 5
== sum_func(2) + 3 + 5
== 2 + 3 + 5
Upvotes: 4
Reputation: 2931
As you say if there's only 1 digit return it.
The % is the modulus
operator - i.e. the remainder when dividing by 10, or simply the last digit (i.e. 235%10 = 5)
int(n/10) drops the last digit since the int() function rounds down - i.e. 235 -> 23
Now what you seem to be confused by is within sum_func
it calls sum_func
again with the remainder once the last digit has been dropped i.e. 23 (this is the recursion part) which will then return 5.
i.e. you have
sum_func(235)
=5 + sum_func(23)
=5 + (3 + sum_func(2))
=5 + (3 + (2))
=10
Upvotes: 2