LeetCode #258. Add Digits,
Add Digits
Description:
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:Cocould you do it without any loop/recursion in O (1) runtime?
Hint:A naive implementation of the above process is trivial. cocould you come up with other methods?
Question:
Given a non-negative integer num, add each digit repeatedly until the result has only one digit.
For example:
Given num = 38, the process is like this: 3 + 8 = 11, 1 + 1 = 2. Because 2 has only one digit, return it.
Further consideration:
Can you finish the question during the O (1) running time without repeating?
Tip:
An intuitive solution is to simulate the above process. Can you think of other methods?
How many possibilities are the results?
Are they periodic or random?
Solution:
Observation method
As prompted, the result is only one digit, so the possible number is 0-9.
Use method I code to output the running result of 0-19 cyclically:
''In out in out
0 0 10 1
1 1 11 2
2 2 12 3
3 3 13 4
4 4 14 5
5 5 15 6
6 6 16 7
7 7 17 8
8 8 18 9
9 9 19 1''
The relationship between output and input is as follows:
''Out = (in-1) % 9 + 1''
C ++ code:
1 class Solution {2 public:3 int addDigits(int num) {4 return (num-1)%9+1;5 }6 }