File tree 5 files changed +64
-8
lines changed
solution/0200-0299/0258.Add Digits
5 files changed +64
-8
lines changed Original file line number Diff line number Diff line change 21
21
22
22
<!-- 这里可写通用的实现逻辑 -->
23
23
24
+ 题目要求的数叫做“数根”,我们把 1~ 30 的数根列出来:
25
+
26
+ ```
27
+ 原数: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
28
+ 数根: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3
29
+ ```
30
+
31
+ 可以看到,数根 9 个为一组,循环出现。我们可以得出下面的规律:
32
+
33
+ - n = 0:数根是 0
34
+ - n 是 9 的倍数:数根是 9
35
+ - n 不是 9 的倍数:数根是 n % 9
36
+
37
+ 将上面的规律用式子:` (n - 1) % 9 + 1 ` 统一表达。
38
+
24
39
<!-- tabs:start -->
25
40
26
41
### ** Python3**
27
42
28
43
<!-- 这里可写当前语言的特殊实现逻辑 -->
29
44
30
45
``` python
31
-
46
+ class Solution :
47
+ def addDigits (self , num : int ) -> int :
48
+ return 0 if num == 0 else (num - 1 ) % 9 + 1
32
49
```
33
50
34
51
### ** Java**
35
52
36
53
<!-- 这里可写当前语言的特殊实现逻辑 -->
37
54
38
55
``` java
56
+ class Solution {
57
+ public int addDigits (int num ) {
58
+ return (num - 1 ) % 9 + 1 ;
59
+ }
60
+ }
61
+ ```
62
+
63
+ ### ** C++**
39
64
65
+ ``` cpp
66
+ class Solution {
67
+ public:
68
+ int addDigits(int num) {
69
+ return (num - 1) % 9 + 1;
70
+ }
71
+ };
40
72
```
41
73
42
74
### **...**
Original file line number Diff line number Diff line change @@ -31,13 +31,30 @@ Could you do it without any loop/recursion in O(1) runtime?</p>
31
31
### ** Python3**
32
32
33
33
``` python
34
-
34
+ class Solution :
35
+ def addDigits (self , num : int ) -> int :
36
+ return 0 if num == 0 else (num - 1 ) % 9 + 1
35
37
```
36
38
37
39
### ** Java**
38
40
39
41
``` java
42
+ class Solution {
43
+ public int addDigits (int num ) {
44
+ return (num - 1 ) % 9 + 1 ;
45
+ }
46
+ }
47
+ ```
48
+
49
+ ### ** C++**
40
50
51
+ ``` cpp
52
+ class Solution {
53
+ public:
54
+ int addDigits(int num) {
55
+ return (num - 1) % 9 + 1;
56
+ }
57
+ };
41
58
```
42
59
43
60
### **...**
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int addDigits (int num) {
4
+ return (num - 1 ) % 9 + 1 ;
5
+ }
6
+ };
Original file line number Diff line number Diff line change 1
- public class Solution {
2
- public int addDigits (int num ) {
3
-
4
- return 1 + (num - 1 ) % 9 ;
5
-
6
- }
1
+ class Solution {
2
+ public int addDigits (int num ) {
3
+ return (num - 1 ) % 9 + 1 ;
4
+ }
7
5
}
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def addDigits (self , num : int ) -> int :
3
+ return 0 if num == 0 else (num - 1 ) % 9 + 1
You can’t perform that action at this time.
0 commit comments