Sum of Digits (Recursion)

Problem

Read a non-negative integer n. Print the sum of its digits. Solve it with recursion (no loop).

Constraints

  • 0 <= n <= 10^12

Examples

Input

1234

Output

10

Solutions

Best approachTime O(d)Space O(d)

The sum of digits of n is its last digit plus the sum of digits of n / 10. The number gets shorter at each call and reaches the base case.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Sum the digits.
 * Input   : One integer n.
 * Output  : The digit sum.
 * Approach: Split off the last digit.
 * Time    : O(d)
 * Space   : O(d)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(long n) {
        // Step 1: Base case. A number below 10 has only one digit, and this digit is the sum.
        if (n < 10) {
            return n;
        }

        // Step 2: Recursive case. The last digit (n % 10) plus the sum of digits of the rest (n / 10).
        return n % 10 + solve(n / 10);
    }

    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        System.out.println(solve(n));
    }
}
Hints (2)
  1. What is the base case?
  2. How do you get the number without its last digit?