Problem overview
DigitSum receives a non-negative int 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, since the zeros add nothing. A one-digit number is its own sum, and 0 gives 0.
Approach
There is no need to turn the number into text. Two integer operations take it apart:
n % 10is the remainder of dividing by 10, which is the last digit:472 % 10is 2.n / 10with twointvalues drops the remainder, which removes the last digit:472 / 10is 47. Integer division in C# truncates, so there is no fractional part.
Repeat: add the last digit to a running total, then remove it. When the number reaches 0, every digit has been used.
Step by step
- Create
totalas anintset to 0. It holds the sum so far. Ifnis 0, the loop below never runs and 0 is the correct answer. - Write
while (n > 0). Each pass handles one digit, and the loop ends when none are left. - Add
n % 10tototalwith+=. - Divide
nby 10 and store the result back inn. Without this linennever changes and the loop never ends. - Return
totalafter the loop.
For n = 472, the passes look like this:
| Pass | Last digit | total after adding | n after dividing |
|---|---|---|---|
| 1 | 2 | 2 | 47 |
| 2 | 7 | 9 | 4 |
| 3 | 4 | 13 | 0 |
Then n is 0, the loop stops, and the method returns 13.
The solution in C#
class Solution {
public int DigitSum(int n) {
int total = 0;
while (n > 0) {
total += n % 10;
n = n / 10;
}
return total;
}
}
The parameter n is a copy of the caller's number, so changing it inside the method doesn't affect the caller. The order of the two lines in the loop matters: read the last digit first, then drop it.
What the loop keeps true
Two facts hold at the start of every pass. First, total is the sum of the digits already removed. Second, n holds the digits not yet removed. At the start both are as expected: nothing is removed, total is 0 and n is the whole number. Each pass moves one digit from n into total, so both facts stay true. When n is 0, no digits are left, and total is the sum of all of them. Thinking this way is a good habit for any loop that builds up an answer.
A while loop is the right tool because the number of digits isn't known when the method starts. A for loop with a fixed count would need that number first.
Edge cases and common mistakes
- Zero. The loop is skipped and
totalstays 0. - Zeros inside the number.
1005goes 5, 0, 0, 1: the zeros add 0 and the loop still removes them. The result is 6. - Largest input. A number up to 1,000,000,000 has at most 10 digits, and the digit sum is far below the
intlimit, so nothing overflows. For1000000000the answer is 1. - Swapped lines. If you divide before adding, you add the wrong digit and skip the first one.
- Using
/expecting decimals. With twointvalues,/never gives a fraction. That is what makes this work here.
Testing
The solution returns 13 for 472, 6 for 1005, 7 for 7 and 0 for 0.
