-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDigitalRoot.java
More file actions
51 lines (41 loc) · 1.26 KB
/
Copy pathDigitalRoot.java
File metadata and controls
51 lines (41 loc) · 1.26 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
package kyu6;
public class DigitalRoot {
//6
public static int digitalRootRecursiveStream(int n) {
return n < 10 ? n : digitalRootRecursiveStream(String.valueOf(n)
.chars()
.map(i -> Character.digit((char) i, 10))
.sum());
}
public static int digitalRoot(int n) {
if (n < 10) return n;
int temp = n;
int result;
do {
result = 0;
while (temp > 0) {
result = result + temp % 10;
temp /= 10;
}
temp = result;
} while (result > 9);
return result;
}
/**
* Retains compatibility with the original Codewars API.
*
* @param n a non-negative integer
* @return the digital root of {@code n}
* @deprecated use {@link #digitalRoot(int)} instead
*/
@Deprecated
public static int digital_root(int n) {
return digitalRoot(n);
}
/**
* Digital root is the recursive sum of all the digits in a number.
* Given n, take the sum of the digits of n. If that value has more than one
* digit, continue reducing in this way until a single-digit number is produced.
* The input will be a non-negative integer.
*/
}