Sum of Digits
easySave
MathNumber Theory
Given a non-negative integer, compute the sum of its digits until the result is a single digit.
Example 1
Input
[ 123 ]
Output
6
Explanation. The sum of the digits 1+2+3 equals 6, which is already a single digit.
Example 2
Input
[ 999 ]
Output
9
Explanation. The sum of the digits 9+9+9 equals 27. The sum of 2+7 equals 9, which is a single digit.
Example 3
Input
[ 3045 ]
Output
3
Explanation. The sum of the digits 3+0+4+5 equals 12. The sum of 1+2 equals 3, which is a single digit.
Example 4
Input
[ 10 ]
Output
1
Explanation. The sum of the digits 1+0 equals 1.
Example 5
Input
[ 0 ]
Output
0
Explanation. The input is 0, and the sum of a single digit 0 is 0.
Follow-up: How would you modify your solution to handle very large numbers efficiently?
Constraints:
The input integer is a non-negative integer.
- Views
- 2