(Coderbyte) Additive Persistence - Solução

Have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit. For example: if num is 2718 then your program should return 2 because 2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.

Solução:

import java.util.*;
import java.io.*;
import java.lang.*;

class Function { 
  int AdditivePersistence(int num) {
 
    String numero = String.valueOf(num);
    int contador = 0;
    while (numero.length() > 1) {
      int soma = 0;
      for (int i = 0; i < numero.length(); i++) {
           soma += Integer.parseInt(Character.toString(numero.charAt(i)));
      }
      numero = String.valueOf(soma);

      contador++;
    }
      
    return contador;
   
  }
 
  public static void main (String[] args) { 
    // keep this function call here    
    Scanner  s = new Scanner(System.in);
    Function c = new Function();
    System.out.print(c.AdditivePersistence(s.nextLine()));
  }  
 
}           

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução