Loading...
Loading...
A shopkeeper checks a long bill number by adding its digits, then adding the digits of that sum, and so on until one digit is left. That digit is the digital root. For 9875: 9+8+7+5 = 29, 2+9 = 11, 1+1 = 2.
Write two recursive methods (no loops in them): static int digitSum(long n) and static int digitalRoot(long n).
Example 1
Input
9875
Output
2
9875 → 29 → 11 → 2.
Example 2
Input
7
Output
7
Already one digit.
Try the problem first. Open one hint at a time.
Recursive digit sum: the last digit plus the digit sum of the rest, n % 10 + digitSum(n / 10). The base case is n = 0.
Digital root: if n is already below 10, return it; otherwise return the digital root of its digit sum.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor