479.Sum of Digits of a Number
Easy
Given a non-negative integer
n, return the sum of its digits.
The loopExtraction LoopRepeatedly reading the last digit with % 10, adding it to a running total, then removing it with integer division by 10. version is the direct, iterative way to peel digits off one at a time. The recursiveRecursionsumOfDigits(n) = n's last digit + sumOfDigits of everything before it — the same problem, one digit smaller each call. version expresses the exact same idea as "this digit, plus the digit sum of the rest," with 0 as the natural base case.
Example 1:
Input: n = 348
Output: 15
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1001
Output: 2
+ 4 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ n ≤ 1000000000
n =
348