Challenge: Sum of Digits (Recursion)

Lab Java Intermediate 20 points

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
Sample input available Sample output available
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
HOME LABS COMMUNITY DASHBOARD