Skip to content

Commit 76b49c7

Browse files
committed
Additive Persistence
1 parent b142da9 commit 76b49c7

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/easy/AdditivePersistence.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package easy;
2+
3+
/**
4+
* Have the function AdditivePersistence(num) take the num parameter being passed
5+
* which will always be a positive integer
6+
* and return its additive persistence which is the number of times
7+
* you must add the digits in num until you reach a single digit.
8+
* ---
9+
* For example: if num is 2718 then your program
10+
* should return 2 because 2 + 7 + 1 + 8 = 18
11+
* and 1 + 8 = 9, and you stop at 9.
12+
*/
13+
public class AdditivePersistence {
14+
15+
/**
16+
* Additive Persistence function.
17+
*
18+
* @param num input number
19+
* @return additive persistence which is the number of times
20+
*/
21+
private static int additivePersistence(int num) {
22+
int times = 0;
23+
int added = num;
24+
while (added > 9) {
25+
int sum = 0;
26+
String[] intArr = Integer.toString(added).split("");
27+
for (String i : intArr) {
28+
sum += Integer.parseInt(i);
29+
}
30+
added = sum;
31+
times++;
32+
}
33+
return times;
34+
}
35+
36+
/**
37+
* Entry point.
38+
*
39+
* @param args command line arguments
40+
*/
41+
public static void main(String[] args) {
42+
var result1 = additivePersistence(199);
43+
System.out.println(result1);
44+
var result2 = additivePersistence(913);
45+
System.out.println(result2);
46+
}
47+
48+
}

0 commit comments

Comments
 (0)