Additive Persistence - Programming Challenge [Java]
There is this awesome subreddit called r/dailyprogrammer, that posts programming challenges. There was this post about additive persistence.
2. int c = 0;
3. while(n > 9){
4. c++;
5. String s = n + "";
6. n = 0;
7. for (int i = 0; i < s.length(); i++)
8. n += Integer.parseInt(s.charAt(i) + "");
9. }
10. return c;
11. }
1. public int calculateRec(int n){
2. if(n < 10)
3. return 0;
4. else {
5. String s = n + "";
6. n = 0;
7. for (int i = 0; i < s.length(); i++)
8. n += Integer.parseInt(s.charAt(i) + "");
9. return 1 + calculateRec(n);
10. }
11. }
There are some examples on the challenge page. My results match theirs.
You can get the final code on my github page.
The challenge goes like this:
Take an integer N:
- Add its digits
- Repeat until the result has 1 digit
The total number of iterations is the additive persistence of N.
This is what I did:
1. public int calculate(int n){2. int c = 0;
3. while(n > 9){
4. c++;
5. String s = n + "";
6. n = 0;
7. for (int i = 0; i < s.length(); i++)
8. n += Integer.parseInt(s.charAt(i) + "");
9. }
10. return c;
11. }
This is how it Works:
- The function will return an integer, which is the additive persistence of the parameter n.
- The integer variable c will count the iterations of our while-loop. The number of times our while-loop iterates will be the additive persistence of n.
- While the value of n is greater than 9, the length of n is also greater than 1. When this is true, we need the while-loop to execute.
- The while-loop is being executed, and this iteration is counted.
- The String variable s will temporarily store the value of n.
- The integer n will be used to store the new value of n after the calculations.
- This for-loop will iterate over the variable s, where our number is stored.
- The sum of each of the digits of s is stored in n.
- The while-loop will stop executing when n is less than or equal to 9.
- The value of c is the additive persistence of n.
Another Solution:
Besides the simpler solution above, I tried doing it recursively just for fun. This solution turned out to be the same length, but it was kinda fun messing around with recursion.1. public int calculateRec(int n){
2. if(n < 10)
3. return 0;
4. else {
5. String s = n + "";
6. n = 0;
7. for (int i = 0; i < s.length(); i++)
8. n += Integer.parseInt(s.charAt(i) + "");
9. return 1 + calculateRec(n);
10. }
11. }
There are some examples on the challenge page. My results match theirs.
You can get the final code on my github page.
Comments
Post a Comment