Frontend School

Sum of Digits Recursive

DSA
easy

Sum of Digits Recursive

Easy
Recursion
Mathematics
Number Theory

Overview

Oracle's data analytics platforms frequently process large volumes of numerical data, often requiring specific transformations for validation, aggregation, or feature engineering. One fundamental operation is computing the sum of digits of an integer. This problem asks you to implement a recursive solution for this task, emphasizing efficient and elegant code that aligns with best practices for handling numerical data.

What you need to do / Task

Your task is to implement a recursive function, sumDigits, that accepts a non-negative integer n and returns the sum of its individual digits.

Input & output

  • n: A non-negative integer (number type in TypeScript/JavaScript).
  • Returns: The sum of the digits of n (number type).

Clarifications

  • What if n is a single-digit number? The function should return n itself.
  • What if n is 0? The function should return 0.
  • Are negative numbers possible? No, n will always be non-negative as per constraints.

Examples

1

Example 1

Input:

n = 123

Output:

6

Note:

1 + 2 + 3 = 6

2

Example 2

Input:

n = 45

Output:

9

Note:

4 + 5 = 9

3

Example 3

Input:

n = 0

Output:

0

Note:

The sum of digits for 0 is 0.

4

Example 4

Input:

n = 907

Output:

16

Note:

9 + 0 + 7 = 16

Constraints

Constraints & assumptions

  • 0 <= n <= 10^9
  • n is an integer.
  • The solution must be implemented using recursion. Iterative solutions will not receive full credit.

Out of scope

  • Error handling for invalid input types (e.g., non-numeric n). Assume valid input per constraints.
  • Optimization for extremely large numbers that exceed standard number type precision (e.g., using BigInt in JavaScript).

What interviewers evaluate

  • Correctness and Completeness: Does the solution correctly calculate the sum of digits for all valid inputs, including edge cases?
  • Recursive Paradigm Adherence: Is the solution purely recursive, demonstrating a clear understanding of base cases and recursive steps?
  • Time and Space Complexity: Can the candidate analyze and discuss the complexity of their recursive solution?
  • Code Quality: Is the code clean, readable, well-structured, and appropriately commented if necessary?

Loading editor...