Frontend School

Recursive Sum of Digits

DSA
easy

Recursive Sum of Digits

Easy
Recursion
Math
numbers

Overview

In financial technology, data integrity and quick computational checks are crucial. Imagine a scenario where you're validating transaction IDs or account numbers where a simple checksum is derived by summing its digits. This problem provides a foundational exercise in applying recursion to solve such a task efficiently, a pattern often seen in data processing and validation pipelines.

What you need to do / Task

Implement a function sumDigitsRecursive that takes a non-negative integer n and returns the sum of its digits using a recursive approach.

Input & output

  • Input: n: number
    • A non-negative integer.
  • Output: number
    • The sum of the digits of n.

Clarifications

  • What should be the sum of digits for n = 0? The sum of digits for 0 is 0.
  • What if n is a single-digit number? The sum of digits is the number itself (e.g., sum of digits for 5 is 5).

Examples

1

Example 1

Input:

n = 123

Output:

6

Note:

1 + 2 + 3 = 6

2

Example 2

Input:

n = 4509

Output:

18

Note:

4 + 5 + 0 + 9 = 18

3

Example 3

Input:

n = 7

Output:

7

Note:

The sum of digits for a single-digit number is the number itself.

4

Example 4

Input:

n = 0

Output:

0

Note:

The sum of digits for 0 is 0.

Constraints

Constraints & assumptions

  • 0 <= n <= 10^9
  • The input n will always be an integer.

What interviewers evaluate

  • Correct identification and implementation of the base case(s) for recursion.
  • Accurate formulation of the recursive step.
  • Proper handling of edge cases, specifically n = 0 and single-digit numbers.
  • Overall correctness and clarity of the recursive logic.

Loading editor...