Sum of Digits of a Number

Solve this Problem
Easy5–10 min
Topics
Companies
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.

Test Case 1:

Input:n = 348
Output:15
Explanation:3 + 4 + 8 = 15.

Test Case 2:

Input:n = 0
Output:0
Explanation:Zero has no digits to add beyond itself.

Test Case 3:

Input:n = 1001
Output:2
Explanation:1 + 0 + 0 + 1 = 2.

Constraints

  • ◆0 ≤ n ≤ 1000000000

Try the Dry Run

Approach & Solutions

Loop — Extract Last Digit with % 10Good

Repeatedly pull off the last digit with n % 10, add it to a running total, then strip that digit off with n / 10. Keep going until n reaches 0 — every digit gets added exactly once.

TimeO(d) — d is the number of digits
SpaceO(1)
1class Solution { 2 public int sumOfDigits(int n) { 3 int sum = 0; 4 while (n != 0) { 5 sum += n % 10; 6 n = n / 10; 7 } 8 return sum; 9 } 10}
Recursive Digit SumOptimal

sumOfDigits(n) is just n's last digit plus the digit sum of everything before it — sumOfDigits(n / 10). 0 has a digit sum of 0, which is the base case that eventually stops the recursion.

TimeO(d)
SpaceO(d) call-stack space
1class Solution { 2 public int sumOfDigits(int n) { 3 if (n == 0) { 4 return 0; 5 } 6 return n % 10 + sumOfDigits(n / 10); 7 } 8}

Related Problems