http://www.codewars.com/kata/55bf01e5a717a0d57e0000ec/train/java
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit. Eg:
39 = [3*9] = 27 = [2*7] = 14 = [1*4] = 4
therefore the output is 3 (the amount of steps)
我尝试过这个 KATA,但收到错误:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
不知道为什么,请问有人可以帮忙吗?我的代码如下:我认为我处理这个问题的方式非常复杂,但我尝试过其他路线,但无法进一步使用它们。这就是我想出的:我对java和开发很陌生,我认为你可以使用回归来找到解决方案,但我不完全确定。
import java.util.LinkedList;
public class Persist {
static LinkedList<Long> digits = new LinkedList<Long>();
public static void splitNumbersUp(long number){
while(number > 0) {
digits.push(number % 10);
number /= 10;
}
}
public static void clearDigits(){
digits.clear();
}
public static long multiply(int length){
long variable = 0;
for(int i = 0 ; i < digits.size(); i++){
variable = digits.pop() * digits.pop();
digits.push(variable);
}
return variable;
}
public static int persistence(long n) {
long num = 0;
if(n > 10){
while(!((digits.get(0) / 10) >= 1)){
splitNumbersUp(n);
num = multiply(digits.size());
clearDigits();
digits.push(num);
}
int i = (int)digits.get(0).intValue();
return i;
}else{
return 0;
}
}
}
最佳答案
我相信这个函数首先被调用?
public static int persistence(long n) {
long num = 0;
if(n > 10){
while(!((digits.get(0) / 10) >= 1)){
splitNumbersUp(n);
num = multiply(digits.size());
clearDigits();
digits.push(num);
}
...
在这种情况下,问题是数字为空,但您尝试获取其中的元素。
如果我正确地阅读了您的代码,请将其更改为:
public static int persistence(long n) {
long num = 0;
splitNumbersUp(n); //This before the for loop
if(n > 10){
while(!((digits.get(0) / 10) >= 1)){
splitNumbersUp(n);
num = multiply(digits.size());
clearDigits();
digits.push(num);
}
应该可以
关于java - CodeWars : Persistent Bugger. 需要解释+建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36095153/