Problem overview
The method 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 5 + 0 + 0 + 1 = 6, and for a single digit like 7 it is 7 itself. The sum for 0 is 0.
Approach
A number does not give its digits directly, but two operations take them off one at a time. The remainder n % 10 is the last digit: 472 % 10 is 2. Dividing by 10 and dropping the fraction removes that digit: 472 becomes 47. Repeat until nothing is left, adding each last digit to a running total.
In TypeScript, / is ordinary division of doubles, so 472 / 10 is 47.2, not 47. Wrapping the result in Math.floor rounds it down to 47. For non-negative numbers, Math.floor and Math.trunc agree.
Here is what the loop does with 472:
| n at the start of the turn | n % 10 | total after adding |
|---|---|---|
| 472 | 2 | 2 |
| 47 | 7 | 9 |
| 4 | 4 | 13 |
After the third turn n is 0, the condition n > 0 fails, and the total, 13, is the answer.
Step by step
- Declare
totalwithletas anumber, starting at 0. It usesletbecause it changes inside the loop. Ifnis 0, the loop never runs and 0 is already right. - Write a
whileloop that runs as long asn > 0. Each turn removes one digit, so the loop ends when every digit is gone. - Add the last digit:
total += n % 10. - Drop the last digit:
n = Math.floor(n / 10). Without this linennever changes and the loop never ends. - Return
totalafter the loop.
The solution in TypeScript
class Solution {
digitSum(n: number): number {
let total: number = 0;
while (n > 0) {
total += n % 10;
n = Math.floor(n / 10);
}
return total;
}
}
- The parameter is changed. Assigning to
nis allowed. The caller's number is not affected, because numbers are passed by value. : numberis only a label. TypeScript removes it when compiling to JavaScript. The type does not makenan integer: anumberis a double.- Large inputs are fine. Doubles hold every integer exactly up to 2^53, far above the limit of 10^9, and there is no integer overflow to worry about.
digitSum(1000000000)returns 1.
Complexity
Time: O(log n). The loop runs once per digit, and a number n has about log10(n) digits. For the limit of 10^9 that is at most 10 turns.
Space: O(1). Only total is added.
Edge cases and common mistakes
- Zero. The loop is skipped and the function returns 0.
- Zeros inside the number. 1005 gives 6: each 0 is a turn that adds nothing.
- Forgetting
Math.floor.n / 10turns 472 into 47.2, then 4.72, and so on. The remainders become fractions such as 4.72 % 10, so the loop runs far longer than the number of digits and the total is wrong. - Using
constfortotal. The compiler reports an error ontotal +=, since a constant cannot be reassigned. - Looping while
n >= 0. The condition never becomes false, becauseMath.floor(0 / 10)is 0 again.
Testing
n = 472gives13.n = 1005gives6.n = 7gives7.n = 0gives0.n = 1000000000gives1.
