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: 13

Explanation: 4 + 0 + 7 + 2 = 13. The 0 adds nothing, but the digits after it still count.

Example 2

Input: n = 0

Output: 0

Example 3

Input: n = 999999999999999

Output: 135

Explanation: 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.