Problem overview
The function digitSum receives a non-negative integer n and returns the sum of its digits. For 472 the digits are 4, 7 and 2, so the answer is 13. For 1005 it is 6, because the zeros add nothing. A one-digit number is its own sum, and 0 gives 0.
Approach
A number doesn't hand you its digits, but two operators do. The remainder n % 10 is the last digit (472 % 10 is 2). Integer division n / 10 removes the last digit (472 / 10 is 47). So the plan is a loop: add the last digit to a running total, drop it, and repeat until nothing is left.
Here is the loop on 472, with the values printed after each pass:
| Pass | Digit added | num after | total after |
|---|---|---|---|
| 1 | 2 | 47 | 2 |
| 2 | 7 | 4 | 9 |
| 3 | 4 | 0 | 13 |
After the third pass num is 0, the loop stops, and 13 is the answer.
Step by step
- Copy
nintonum. Function parameters in Kotlin are read-only, so the loop can't changen. Avarvariable can be reassigned, so the loop takes digits offnuminstead. - Start
totalat 0. Nothing has been added yet. Forn = 0the loop never runs, and 0 is the right answer. - Loop while
num > 0. Each pass removes one digit, sonumreaches 0 when all digits are gone. - Add the last digit.
total += num % 10. - Drop the last digit. Store
num / 10back innum. Without this line the loop never ends. - Return
totalafter the loop.
The solution in Kotlin
class Solution {
fun digitSum(n: Int): Int {
var num = n
var total = 0
while (num > 0) {
total += num % 10
num = num / 10
}
return total
}
}
Some details worth knowing:
/on twoIntvalues drops the remainder.47 / 10is 4, not 4.7. That is what makes it remove a digit.varversusval. Assigning to aval, or to the parametern, is a compile error:'val' cannot be reassigned.Intis enough. The largest input, 1000000000, fits in anInt, and its digit sum is 1.
Why a while loop
A for loop is for a known number of repetitions, such as the characters of a string. Here the number of passes depends on how many digits n has, and the code doesn't know that count beforehand. A while loop repeats until a condition fails, which is the natural fit: keep going while there are digits left. The condition num > 0 is also what makes the empty case, n = 0, work without any special handling.
The same pair of operations, % 10 and / 10, is the standard way to take a number apart in any base-10 exercise. Counting digits, reversing a number and checking palindromes are all variations on this loop.
Complexity
Time is O(d), where d is the number of digits, because each pass removes one. Space is O(1): two variables.
Edge cases and common mistakes
- Zero.
num > 0is false at once, so the function returns 0. - Forgetting
num = num / 10.numnever changes and the loop runs forever. - Using
valfortotal. The code won't compile, sincetotalchanges in the loop. - Zeros inside the number.
1005passes through 5, 0, 0, 1; the zeros add 0 and the loop still removes them.
Testing
472gives13.1005gives6.7gives7.0gives0.1000000000gives1.
