Sum of digits
A checksum routine needs the digits of a number added together.
- Negative input uses its digits too: -204 sums to 6.
- The digits of 0 sum to 0.
DigitSum(amount: int) → int
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public int DigitSum(int amount) {
}
Worked examples
| Call | Result |
|---|---|
DigitSum(0) | 0 |
DigitSum(7) | 7 |
DigitSum(1234) | 10 |
DigitSum(-204) | 6 |
Hint
Take the absolute value first, then peel digits off with % 10 and / 10.
Reference solution in C#
public int DigitSum(int amount) {
int x = Math.Abs(amount), total = 0;
while (x > 0) { total += x % 10; x /= 10; }
return total;
}