Java program does not return Int

I am trying to run a program on CodeWars, and one of the requirements is that the persistent () function returns an int. I am having trouble forming it in such a way that it always returns an int. Any help is much appreciated!

public class Persist { public static int persistence(int n) { int product = n; int numReiterations = 0; while (length(product) != 1) { product = multiplyDigits(product); numReiterations++; } if (length(product) == 1) return numReiterations; } public static int multiplyDigits(int num) { int product = 1; for (int x=0; x<String.valueOf(num).length(); x++) { char numChar = String.valueOf(num).charAt(x); int numBack = Integer.parseInt(String.valueOf(numChar)); product *= numBack; } return product; } public static int length(int product) { return String.valueOf(product).length(); } } 
+4
source share
3 answers

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 
+4
source

You should always have at least one return statement outside any if / else block if the function should return something.
Not only in Java, but also in any similar, strongly typed language.

After if(length(product==1)) block , return -99999999 or some error code, if this return should not be damaged during normal operation.

0
source

Your while only ends when length(product) is 1. So just return numIterations by removing the if condition.

0
source

All Articles