Avatar of gudii9
gudii9
Flag for United States of America asked on

sumDigits challenge

Hi,

http://codingbat.com/prob/p163932

I am working on above challenge
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

i was not sure how to find the sum of digits recursively without loop which i worked earlier. please advise
JavaJava EEProgramming Languages-OtherProgrammingProgramming Theory

Avatar of undefined
Last Comment
rrz

8/22/2022 - Mon
d-glitch

Do you remember how to break up an integer into the LAST digit and the REST using % and / .

Recursion works by letting a function call itself multiple times, each time with a smaller or simpler argument.

The pseudo code would be something like:
function sumDigits( n)
sum = 0
if arg = 0 
     return sum
else
     sum = sum + LAST( arg) + sumDigits( REST( arg))

Open in new window


RECURSION is probably the single most important and elegant topic in computer science.
You should really read up on it if you don't understand the concept.  Challenges are not going to be enough.
gudii9

ASKER
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.
You should really read up on it if you don't understand the concept.  Challenges are not going to be enough.
where should i read up on it? Any best material,book, site?
ASKER CERTIFIED SOLUTION
d-glitch

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
rrz

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
gudii9

ASKER
I will try
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
gudii9

ASKER
public int sumDigits(int n) {
  if (n < 10) 
{return n;
}
  return (n % 10) + sumDigits(n/10);
}

Open in new window


above passes all test. any improvements or alternate approaches?
rrz

 if (n < 10)
{return n;
Brilliant! I like your base case much better.