Additive Persistence - Programming Challenge [Java]

There is this awesome subreddit called r/dailyprogrammer, that posts programming challenges. There was this post about additive persistence.

The challenge goes like this:

Take an integer N:
  1. Add its digits
  2. 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:

  1.  The function will return an integer, which is the additive persistence of the parameter n.
  2. 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.
  3. 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.
  4. The while-loop is being executed, and this iteration is counted.
  5. The String variable s will temporarily store the value of n.
  6. The integer n will be used to store the new value of n after the calculations.
  7. This for-loop will iterate over the variable s, where our number is stored.
  8. The sum of each of the digits of s is stored in n. 
  9. The while-loop will stop executing when n is less than or equal to 9.
  10. 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

Popular posts from this blog

A* Pathfinding Algorithm Java Implementation