Challenge: Digital Root
Completed
The digital root of a number: add up its digits; if the result has more than one digit, add up its digits, and so on until one digit is left. Write it recursively.
Input
One whole number n (0 ≤ n ≤ 2,000,000,000).
Output
The digital root.
Example
Input
9875
Output
2
Editor
Java
Hints
First write digitSum(n) = last digit + digitSum(n / 10).
digitalRoot(n): if n has one digit, return it; otherwise return digitalRoot(digitSum(n)).
Solution explanation
9875 → 29 → 11 → 2. Two small recursive methods, each with a clear base case.
Show solution
import java.util.Scanner;
public class Main {
static long digitSum(long n) {
if (n < 10) return n;
return n % 10 + digitSum(n / 10);
}
static long digitalRoot(long n) {
if (n < 10) return n;
return digitalRoot(digitSum(n));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
System.out.println(digitalRoot(n));
}
} 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