DSA Factory
Free lessonsMath and bits · Stage 0 · Digits and divisibility · Step 1

Peel off the last digit

Walk through a number's digits with % 10 and // 10. About 6 minutes.

Peel the last digit off

Think of a number as a stack of digit cards. Divide 4729 by 10 and the remainder is 9, which is exactly the last digit. Whole-number division by 10 gives 472, which is the same number with that last digit torn off.

Two small moves give you everything: read the last digit, then drop it.

Remainder after dividing by 10: is the last digit.
Whole-number division by 10: drops the last digit.
In code
4729 % 10    # 9
4729 // 10   # 472
Digits of 4729, right to left
4
0
7
1
2
2
9
3
digit

4729 % 10 = 9. total = 9, n becomes 472.

Move 1 of 4

Repeat until nothing is left

Do it again and again. Read the last digit, add it to a running total, then drop it. When the number reaches 0 there are no digits left, so you have met every one of them, from right to left.

What if the number is 0 to begin with? The loop never runs and the total stays 0, which is the right answer for a sum.

In Java and C++: dividing two whole numbers already rounds down for positive values.
In code
total = 0
while n > 0:
    total += n % 10
    n //= 10
return total
Quick check

What are 5308 % 10 and 5308 // 10?

  1. A8 and 530
  2. B530 and 8
  3. C5 and 308
Show the answer

8 and 530. The remainder is the last digit, 8, and dividing drops it, leaving 530.

Your problem

Sum of the digits

Return the sum of the digits of n. The digits of 0 add up to 0.

Example
n = 4729 → 22

0 ≤ n ≤ 2,000,000,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding