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 % 10is the remainder after dividing by 10, which is the last digit:472 % 10is 2.n / 10on two integers drops the remainder, which removes the last digit:472 / 10is 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:
| Pass | Digit added | n afterwards | total |
|---|---|---|---|
| 1 | 2 | 47 | 2 |
| 2 | 7 | 4 | 9 |
| 3 | 4 | 0 | 13 |
Once n is 0 the condition n > 0 is false and the loop ends.
Step by step
- Create
totalwith:=, starting at 0. No digit has been added yet. Ifnis 0, the loop never runs and 0 is already the right answer. - Write the loop with only a condition,
n > 0. Each pass removes one digit, sonreaches 0 when all digits are gone. Write the closing brace right away. - Add
n % 10tototalwith+=. That is the current last digit. - Drop the last digit by storing
n / 10back inn. Without this linennever changes and the loop never ends. - Return
totalafter 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. Withnnon-negative,%and/behave the way this loop needs. - Order matters. The remainder must be added before
nis 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. Anintin Go is 64 bits here, so the biggest input fits easily. - Forgetting
n = n / 10. The loop then runs forever on any positiven. - Using
n >= 0. That loop would never stop, because 0 stays 0.
Testing
472gives 13.1005gives 6.7gives 7.0gives 0.1000000000gives 1.
