45.8k views
2 votes
Write a recursive method named sumDigits that computes and returns the sum of the digits in a long integer. For example, sumDigits(234) returns 2+3+4=9. You do not need to test your method with a driver program.

User Kds
by
8.3k points

1 Answer

6 votes

Final answer:

A recursive method named sumDigits is requested to compute the sum of digits in a long integer. The method uses recursion by breaking down the number and summing individual digits until the base case is reached.

Step-by-step explanation:

The student has asked for a recursive method named sumDigits that computes the sum of the digits in a long integer. To define such a method, we consider the base case where the number is less than 10, and the recursive case where the number is 10 or greater. In the base case, the sum of the digits is the number itself, as there is only one digit. In the recursive case, we add the last digit of the number to the sum of the digits of the number divided by 10.

Here is an example of how the method might be implemented in a programming language:

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

This code will recursively call itself until it breaks the number down to individual digits and then sum those digits together.

User Ankit Aman
by
8.6k points