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 0 it is 0. A number with one digit is its own digit sum: 7 gives 7.
Approach
You can't index into an Int to get its digits, but two arithmetic operations give you the same thing.
num % 10is the remainder of dividing by 10, which is the last digit:472 % 10is 2.num / 10on twoIntvalues drops the remainder, which removes the last digit:472 / 10is 47.
Repeat both until nothing is left. Here are the values for 472, taken from a run of the solution:
| num | num % 10 | total after adding |
|---|---|---|
| 472 | 2 | 2 |
| 47 | 7 | 9 |
| 4 | 4 | 13 |
After the third turn, num is 0 and the loop stops. The total, 13, is the answer.
The same two operations work for any task that looks at a number digit by digit: counting digits, reversing a number or finding the largest digit. In each case the loop reads the last digit with % 10 and removes it with / 10.
Step by step
- Copy
nintovar num. Function parameters are constants in Swift, so the loop can't changen. Avarcan be reassigned, and aletcan't. - Create
var total = 0. Nothing has been added yet. Ifnis 0, the loop never runs and 0 is already the right answer. - Loop while
num > 0. Each turn removes one digit, sonumreaches 0 once all of them are gone. - Add
num % 10tototalwith+=. - Replace
numwithnum / 10. Without this line,numnever changes and the loop never ends. - Return
totalafter the loop.
The solution in Swift
class Solution {
func digitSum(_ n: Int) -> Int {
var num = n
var total = 0
while num > 0 {
total += num % 10
num = num / 10
}
return total
}
}
Swift details worth knowing:
- Integer division truncates. Dividing two
Intvalues gives anInt, and the fractional part is dropped:7 / 2is 3. For the non-negative numbers here, truncating and rounding down are the same thing. - No parentheses around the condition. Swift's
whiletakes the condition without them, but the braces are required. - Shorter form.
num /= 10means the same asnum = num / 10. - No overflow worries.
Intis 64 bits, so values up to a billion fit easily, and the digit total is at most 81 for numbers below a billion.
Edge cases and common mistakes
- Zero.
digitSum(0)skips the loop and returns 0. - Zeros inside a number. For 1005, the loop adds 5, 0, 0 and 1, and the total is 6.
- Forgetting
num = num / 10. The loop repeats forever with the same last digit. - Returning inside the loop. The function would stop after the first digit.
- Using
letfortotal. A constant can't be changed by+=, so the code doesn't compile.
Testing
472gives 13.1005gives 6.7gives 7.0gives 0.1000000000gives 1.999999999gives 81.
