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.
4729 % 10 # 9 4729 // 10 # 472
4729 % 10 = 9. total = 9, n becomes 472.
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.
total = 0
while n > 0:
total += n % 10
n //= 10
return totalWhat are 5308 % 10 and 5308 // 10?
- A8 and 530
- B530 and 8
- C5 and 308
Show the answer
8 and 530. The remainder is the last digit, 8, and dividing drops it, leaving 530.
Sum of the digits
Return the sum of the digits of n. The digits of 0 add up to 0.
n = 4729 → 22
0 ≤ n ≤ 2,000,000,000