Sum of digits
Return the sum of the digits of the whole number n. For 1234 that is 1 + 2 + 3 + 4 = 10. Try it with % and integer division, not by turning n into text.
Write sum_of_digits(n) in Python, sumOfDigits(n) in JavaScript or TypeScript, or int sum_of_digits(int n) in C. Level: Easy.
Examples
Input: n = 1234 Output: 10
Input: n = 0 Output: 0
- 0 ≤ n ≤ 10^12
Hint
n % 10 is the last digit, and dividing by 10 (whole number division) drops it. In JavaScript use Math.floor(n / 10).
The approach, step by step
- total = 0
- n > 0?
- total = total + n % 10
- n = n // 10
- Return total