Start learning free

LESSON 215 OF 285 · WHILE LOOPS - CHALLENGES

Digit Sum in Go: A for 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

    GO · WHILE LOOPS - CHALLENGES

    Digit Sum in Go, 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, and the sum is 13. For n = 1005 it is 6, because the zeros add nothing. A one-digit number is its own digit sum, and n = 0 gives 0.

    Approach

    An int doesn't give you its digits directly, but two operators do the job:

    • n % 10 is the remainder after dividing by 10, which is the last digit: 472 % 10 is 2.
    • n / 10 on two integers drops the remainder, which removes the last digit: 472 / 10 is 47.

    So the plan is to add the last digit to a running total, drop it, and repeat until nothing is left. Go has no while keyword. A for loop with only a condition does the same job, here for n > 0.

    Tracing n = 472, these are the values of n and total at the end of each pass:

    PassDigit addedn afterwardstotal
    12472
    2749
    34013

    Once n is 0 the condition n > 0 is false and the loop ends.

    Step by step

    1. Create total with :=, starting at 0. No digit has been added yet. If n is 0, the loop never runs and 0 is already the right answer.
    2. Write the loop with only a condition, n > 0. Each pass removes one digit, so n reaches 0 when all digits are gone. Write the closing brace right away.
    3. Add n % 10 to total with +=. That is the current last digit.
    4. Drop the last digit by storing n / 10 back in n. Without this line n never changes and the loop never ends.
    5. Return total after the loop.

    The solution in Go

    func digitSum(n int) int {
        total := 0
        for n > 0 {
            total += n % 10
            n = n / 10
        }
        return total
    }
    

    Go details:

    • Parameters are copies. The loop changes n, but only the function's own copy. The caller's variable is untouched.
    • Integer division truncates. Both operands are int, so / gives a whole number. With n non-negative, % and / behave the way this loop needs.
    • Order matters. The remainder must be added before n is divided, or the last digit is lost.

    Complexity

    The loop runs once per digit. A number up to a billion has at most ten digits, so the time is proportional to the number of digits, and the extra space is a couple of integers: total and the function's own copy of n. The work doesn't depend on how large the digits are, only on how many there are.

    Edge cases and common mistakes

    • Zero. digitSum(0) returns 0 without entering the loop.
    • Trailing zeros. digitSum(1005) adds 5, 0, 0, 1 and returns 6.
    • The largest input. digitSum(1000000000) returns 1, after ten passes. An int in Go is 64 bits here, so the biggest input fits easily.
    • Forgetting n = n / 10. The loop then runs forever on any positive n.
    • Using n >= 0. That loop would never stop, because 0 stays 0.

    Testing

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