Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
48 lines (40 loc) · 1.14 KB

File metadata and controls

48 lines (40 loc) · 1.14 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
E
1519709532
tags: Math
方法1: 普通做法就是按照题意, double-while loop把数字加起来. 第一层循环是O(n), 然后第二层循环就少很多数位, overall O(n)
方法2: 找数学规律, 每过9个数字, 取mod就会开始重复, 所以给所有数字取mod 就可以间接找到答案. O(1)
```
/*
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:
Could you do it without any loop/recursion in O(1) runtime?
*/
/*
Thoughts:
Keep adding until result < 10
Double-while loop: start with a num, calculate result, then num = result.
*/
class Solution {
public int addDigits(int num) {
if (num < 10) {
return num;
}
while (num > 9) {
int temp = 0;
while (num != 0) {
temp += num % 10;
num = num / 10;
}
num = temp;
}
return num;
}
}
class Solution {
public int addDigits(int num) {
return (num - 1) % 9 + 1;
}
}
```
Morty Proxy This is a proxified and sanitized view of the page, visit original site.