Problem overview
The function digitSum receives a non-negative integer n, up to 1,000,000,000, and returns the sum of its digits. The number 472 has the digits 4, 7 and 2, so the answer is 13. The number 1005 gives 5 + 0 + 0 + 1 = 6, because zeros add nothing, and a one-digit number such as 7 is its own digit sum. For n = 0 the sum is 0.
Approach
The number is stored as a value, not as a list of digits, so the function takes the digits off one at a time using two integer operations:
n % 10is the remainder of dividing by 10, which is the last digit:472 % 10is 2.n / 10between twointvalues drops the remainder, which removes the last digit:472 / 10is 47.
Repeating "add the last digit, then drop it" until nothing is left visits every digit exactly once, from the right. When the number has become 0, there are no digits left, so the loop condition is n > 0.
Here is the loop on n = 472, showing the state after each pass:
n=47 total=2
n=4 total=9
n=0 total=13
Step by step
- Create
totalas anintstarting at 0. Nothing has been added yet. Ifnis 0, the loop never runs and 0 is already the right answer. - Start a
whileloop that runs whilen > 0. Each pass removes one digit, sonreaches 0 once every digit is gone. - Add
n % 10tototal. This is the last digit of the currentn. - Replace
nwithn / 10. Without this linennever changes and the loop never ends. - Return
totalafter the loop.
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;
}
};
Some C++ details:
- Integer division. When both operands are
int,/gives anintand the fractional part is discarded. That is exactly the "drop the last digit" behaviour. Dividing by10.0instead would give a fractional result. nis a copy. The parameter is passed by value, so the loop changes only the function's own variable, and the caller's number stays the same.- The range fits in
int. The largest allowed input, 1,000,000,000, is below the 32-bit limit of 2,147,483,647, and the digit sum is tiny compared with it: 999999999 gives 81.
Edge cases and common mistakes
- Zero. The condition
n > 0is false at the start, so the function returns 0. - Trailing zeros. For 1005 the loop adds 5, 0, 0 and 1. The zeros pass through harmlessly.
- The largest input. For 1000000000 the answer is 1, after nine passes that add 0 and a last pass that adds 1.
- Forgetting
n = n / 10. The loop then repeats forever with the same last digit. - Using
n >= 0. Since0 / 10is 0,nnever becomes negative and the loop would never stop.
Testing
n = 472gives 13.n = 1005gives 6.n = 7gives 7.n = 0gives 0.n = 999999999gives 81.n = 1000000000gives 1.
