Given a non-negative int n, return the sum of its digits recursively (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
sumDigits(126) → 9
sumDigits(49) → 13
sumDigits(12) → 3
function sumDigits( n)
sum = 0
if arg = 0
return sum
else
sum = sum + LAST( arg) + sumDigits( REST( arg))
Do you remember how to break up an integer into the LAST digit and the REST using % and / .yes
RECURSION is probably the single most important and elegant topic in computer science.where should i read up on it? Any best material,book, site?
You should really read up on it if you don't understand the concept. Challenges are not going to be enough.
function sumDigits( n)
if n = 1
return 1
else
return LAST + sumDigits( REST)
If you are experiencing a similar issue, please ask a related question
Title | # Comments | Views | Activity |
---|---|---|---|
netstat -ano | find "8000" and taskkill /f /pid 2984 | 3 | 57 | |
javap bin | 2 | 34 | |
servlet example | 11 | 40 | |
ejb on wildfly | 5 | 20 |
Join the community of 500,000 technology professionals and ask your questions.