I would not use lowercase arithmetic at all. In addition, you no longer need to check the length of the number, since you know that it must be 1 , you just left the while loop.
If you use string processing, it is not only longer, but also much slower. I would also use long instead of int , since this allows you to significantly increase the number at a low cost.
public static int persistence(long n) { int numReiterations = 0; for (long product = n; !isSingleDigit(product); product = multiplyDigits(product)) numReiterations++; return numReiterations; } public static long multiplyDigits(long num) { long product = 1; for (; num > 0; num /= 10) product *= num % 10; return product; } public static boolean isSingleDigit(long n) { return n <= 9; } public static void main(String[] args) { System.out.println(persistence(99999999999999999L)); }
prints
3
source share