Beginner ยท digit peeling
Digit Sum
Sum the digits of an integer: 1234 โ 1+2+3+4 = 10. Same peel loop as Count the Digits, but accumulating this time.
Problem
Input: one integer n (โ10โน โค n โค 10โน).
Output: the sum of its digits (the minus sign doesn't count).
Sample:
| Input | Output |
|---|---|
1234 | 10 |
-305 | 8 |
Your solution
Custom input for "Run my input"
Judging runs entirely in your browser against hidden tests. Your code is saved locally as you type. Ctrl+Enter judges.
Stuck? Hints
Hint 1 โ peel and add
Each pass: sum += n % 10; takes the last digit, n = n / 10; drops it. Loop until zero.
Hint 2 โ the traps
Negative input loops forever with n > 0 โ take Math.Abs(n) first. And n = 0 should print 0 (do-while handles it for free).