Foundations Recursion basics
40. Sum of the Digits of a Number
Easy
Given a whole number n, return the sum of its digits, written in base 10.
For example, the digits of 4072 are 4, 0, 7 and 2, and their sum is 13. The number 0 has one digit, 0, so its sum is 0.
Example 1
Input: n = 4072
Output:
13Explanation: 4 + 0 + 7 + 2 = 13. The 0 adds nothing, but the digits after it still count.
Example 2
Input: n = 0
Output:
0Example 3
Input: n = 999999999999999
Output:
135Explanation: The number has fifteen digits, all 9, and 15 × 9 = 135.
Check your understanding
Work out the answer for this input before you write any code.
n = 9045
Constraints
0 ≤ n ≤ 1015
Clarifying questions
What you would ask an interviewer before writing any code.