DigitsSum
SRM 315 · 2006-08-09 · by Cosmin.ro
SRM 315 · 2006-08-09 · by Cosmin.ro · Brute Force
Problem Statement
Problem Statement
Little Johnny is in the first grade and just found out about addition. He quickly learned the addition table and is becoming bored in class, so he thinks of a game. The game consists of choosing an integer and summing its digits. If the result is a single digit, the game ends. Otherwise, Johnny repeats the process on the result until he gets a single digit.
For example, if Johnny starts with the number 12345, he will add the digits 1 + 2 + 3 + 4 + 5 to get 15. The result is not a single digit, so he will repeat the process to get 1 + 5 = 6. The new result is a single digit, so the game ends.
Johnny is curious to see if his computations are correct, so he asks you what the final result is for the number n.
For example, if Johnny starts with the number 12345, he will add the digits 1 + 2 + 3 + 4 + 5 to get 15. The result is not a single digit, so he will repeat the process to get 1 + 5 = 6. The new result is a single digit, so the game ends.
Johnny is curious to see if his computations are correct, so he asks you what the final result is for the number n.
Constraints
- n will be between 0 and 2147483647, inclusive.
Examples
0)
12345 Returns: 6
The example in the problem statement.
1)
6 Returns: 6
In this simple example, the sum of the digits is 6, so the game ends after just one step.
2)
999999999 Returns: 9
The sum of the digits is 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 + 9 = 81. The process is repeated once more to get 8 + 1 = 9, which is a single digit.
3)
213413512 Returns: 4
4)
314 Returns: 8
Submissions are judged against all 92 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Coding Area
Language: C++17 · define a public class DigitsSum with a public method int lastDigit(int n) · 92 test cases · 2 s / 256 MB per case