Challenge: Sum of Digits (Recursion)
Completed
Write a recursive method static int digitSum(int n) that adds up the digits of n. For example digitSum(482) = 4 + 8 + 2 = 14. Read n and print the result.
Input
One whole number n (0 ≤ n ≤ 2000000000).
Output
The sum of its digits.
Example
Input
482
Output
14
Editor
Java
Hints
n % 10 gives the last digit, n / 10 removes it.
Base case: a number below 10 is its own digit sum.
Solution explanation
Each call peels off the last digit and asks the same question about the rest of the number.
Show solution
import java.util.Scanner;
public class Main {
static int digitSum(int n) {
if (n < 10) return n;
return n % 10 + digitSum(n / 10);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(digitSum(sc.nextInt()));
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module