-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAddDigits.java
More file actions
37 lines (32 loc) · 767 Bytes
/
AddDigits.java
File metadata and controls
37 lines (32 loc) · 767 Bytes
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
package math;
/**
* Description: https://leetcode.com/problems/add-digits
* Difficulty: Easy
*/
public class AddDigits {
/**
* Time complexity: O(log10 n)
* Space complexity: O(1)
*/
public int addDigitsViaLoop(int num) {
int digitalRoot = 0;
while (num > 0) {
digitalRoot += num % 10;
num = num / 10;
if (num == 0 && digitalRoot > 9) {
num = digitalRoot;
digitalRoot = 0;
}
}
return digitalRoot;
}
/**
* Time complexity: O(1)
* Space complexity: O(1)
*/
public int addDigitsViaFormula(int num) {
if (num == 0) return 0;
if (num % 9 == 0) return 9;
return num % 9;
}
}