Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive function called sumDigits with the following signature: public

ID: 3819173 • Letter: W

Question

Write a recursive function called sumDigits with the following signature:

public static long sumDigits(long n)

that computes the sum of the digits in a number repeatedly, until the sum is a single digit.

For example, if we call sumDigits(123456), the following would result:

sumDigits(123456) => 1+2+3+4+5+6 => 21 => 2+1 => 3

so the final answer would be 3.

You must meaningfully use recursion for this lab in order to receive any credit.

Hint: For this problem it might be useful to convert back and forth between longs and strings. This can be done using the Long.parseLong

method and the Long.toString method.

Explanation / Answer

package c;


public class MyNumberSumRec {

static long sum = 0;

public static long sumDigits(long number){

if(number == 0){
return sum;
} else {
sum += (number%10);
sumDigits(number/10);
}
return sum;
}

public static void main(String a[]){
System.out.println(sumDigits(1111111111111111111L)); //L is for long
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote