File tree Expand file tree Collapse file tree 1 file changed +10
-27
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +10
-27
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
- /**
4
- * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
5
-
6
- For example:
7
-
8
- Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
9
-
10
- Follow up:
11
- Could you do it without any loop/recursion in O(1) runtime?
12
-
13
- Hint:
14
-
15
- A naive implementation of the above process is trivial. Could you come up with other methods?
16
- What are all the possible results?
17
- How do they occur, periodically or randomly?
18
- You may find this Wikipedia article: https://en.wikipedia.org/wiki/Digital_root useful.
19
- * */
20
-
21
3
public class _258 {
22
4
23
- //only three cases as the code shows
24
- public int addDigits (int num ) {
25
- if (num == 0 ) {
26
- return 0 ;
5
+ public static class Solution1 {
6
+ //only three cases as the code shows
7
+ public int addDigits (int num ) {
8
+ if (num == 0 ) {
9
+ return 0 ;
10
+ }
11
+ if (num % 9 == 0 ) {
12
+ return 9 ;
13
+ }
14
+ return num % 9 ;
27
15
}
28
- if (num % 9 == 0 ) {
29
- return 9 ;
30
- }
31
- return num % 9 ;
32
16
}
33
-
34
17
}
You can’t perform that action at this time.
0 commit comments