forked from andrei-punko/java-interview-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddDigits.java
More file actions
55 lines (48 loc) · 1.06 KB
/
Copy pathAddDigits.java
File metadata and controls
55 lines (48 loc) · 1.06 KB
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
49
50
51
52
53
54
55
package by.andd3dfx.numeric;
/**
* <pre>
* https://leetcode.com/problems/add-digits/description/
*
* Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
*
* Example 1:
*
* Input: num = 38
* Output: 2
* Explanation: The process is
* 38 --> 3 + 8 --> 11
* 11 --> 1 + 1 --> 2
* Since 2 has only one digit, return it.
*
* Example 2:
*
* Input: num = 0
* Output: 0
* </pre>
*/
public class AddDigits {
public static int addDigits(int num) {
if (num < 10) {
return num;
}
var sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return addDigits(sum);
}
/**
* https://en.wikipedia.org/wiki/Digital_root
*/
public static int addDigits_usingDigitalRoot(int num) {
if (num == 0) {
return 0;
}
var remainder = num % 9;
if (remainder == 0) {
return 9;
}
return remainder;
}
}