Start learning free

LESSON 211 OF 287 · WHILE LOOPS - CHALLENGES

Digit Sum in Python: A While Loop with % and //

Practice Read the full explanation

Given a non-negative integer n, return the sum of its digits.

The digits are the figures from 0 to 9 that n is written with: 472 has the digits 4, 7 and 2. If n is 0, the sum is 0.

The last digit of a number is the remainder of its division by 10 (472 % 10 is 2), and dividing by 10 without the remainder removes that digit (472 becomes 47).

 

Example 1:

Input: n = 472
Output: 13
Explanation: Taking the digits from the right: 2 + 7 + 4 = 13.

Example 2:

Input: n = 1005
Output: 6
Explanation: 5 + 0 + 0 + 1 = 6. The zeros add nothing.

Example 3:

Input: n = 7
Output: 7
Explanation: A number with one digit is its own digit sum.

 

Constraints:

  • 0 <= n <= 109
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · WHILE LOOPS - CHALLENGES

    Digit Sum in Python, explained

    Problem overview

    The function digitSum receives a non-negative integer n and returns the sum of its digits. For n = 472 the digits are 4, 7 and 2, so the answer is 13. For 1005 it is 6, because the zeros add nothing, and for 7 it is 7. For 0 the sum is 0.

    Approach

    An integer has no digits to loop over, the way a string has characters. Arithmetic can pull them off one at a time, though, using two operators:

    • n % 10 is the remainder of dividing by 10, which is the last digit: 472 % 10 is 2.
    • n // 10 is integer division, which drops the last digit: 472 // 10 is 47.

    Repeat both until nothing is left. Add each last digit to a running total, then remove that digit. When n reaches 0, every digit has been counted.

    Step by step

    1. Start total at 0. No digit has been added yet. This also gives the right answer for n = 0, where the loop never runs.
    2. Loop while n > 0. Every turn removes one digit, so the loop runs once per digit.
    3. Add n % 10 to total. That is the current last digit.
    4. Set n to n // 10. Without this line n never changes and the loop never ends.
    5. Return total after the loop.

    Here is the loop on n = 472:

    n at the startn % 10total after addingn after dropping
    4722247
    47794
    44130

    With n at 0 the condition fails and the function returns 13.

    The solution in Python

    class Solution:
        def digitSum(self, n: int) -> int:
            total = 0
            while n > 0:
                total += n % 10
                n = n // 10
            return total
    

    Details worth knowing:

    • // is integer division. It floors the result, so 47 // 10 is 4 and 4 // 10 is 0. Plain / always gives a float: 9 / 2 is 4.5, and a float would not have a last digit to take.
    • Reassigning a parameter. n = n // 10 changes only the local name n. The caller's variable is not affected, because integers are immutable.
    • Big numbers are fine. Python integers don't overflow. For 999999999 the function returns 81, and for 1000000000 it returns 1.
    • The string shortcut. sum(int(d) for d in str(472)) also gives 13. The loop above uses only arithmetic, which is the point of this lesson.

    Why it works

    A number such as 472 is really 4 * 100 + 7 * 10 + 2. The remainder after dividing by 10 isolates the part that is not a multiple of 10, which is the last digit, and the integer division keeps everything above it. Since addition doesn't care about order, taking the digits from the right gives the same total as reading them from the left. The loop runs once per digit, so at most ten times for the largest allowed input.

    Python can also do both operations in one call: divmod(472, 10) returns (47, 2), the quotient and the remainder. A loop written as n, d = divmod(n, 10) followed by total += d gives 13 for 472, the same as the version above.

    Edge cases and common mistakes

    • Zero. digitSum(0) returns 0: the loop condition is false at once.
    • Zeros inside the number. 1005 gives 5 + 0 + 0 + 1 = 6. The zero digits are added, and they change nothing.
    • Forgetting to shrink n. If the n = n // 10 line is missing, or is outside the loop, the program runs forever.
    • Using n >= 0. Since 0 // 10 is 0, n would never become negative and the loop would never stop.
    • Returning inside the loop. The function must return after the loop, once all digits are added.

    Testing

    • 472 gives 13.
    • 1005 gives 6.
    • 7 gives 7.
    • 0 gives 0.
    • 999999999 gives 81.
    • 1000000000 gives 1.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free