这是我为IsFibo HackerRank问题想到的解决方案。 (https://www.hackerrank.com/challenges/is-fibo)。我想知道为什么它不会为5返回“ IsFibo”。我的逻辑可能有误,如果有人指出我的错误,我将不胜感激。这是代码:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static ArrayList<BigInteger> fibList = new ArrayList<BigInteger>();
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int numCases = in.nextInt();
fibList.add(BigInteger.valueOf(0));
fibList.add(BigInteger.valueOf(1));
while(in.hasNextLine()) {
System.out.println(checkFibo(in.nextBigInteger()));
System.out.println(fibList);
}
}
public static String checkFibo(BigInteger i) {
int lastIndex = fibList.size() - 1;
int compareRes = i.compareTo(fibList.get(lastIndex));
System.out.println("Last fib num: " + fibList.get(lastIndex));
System.out.println("CompareRes: " + compareRes);
switch(compareRes) {
case 0:
return "IsFibo";
case 1:
BigInteger newFib = fibList.get(lastIndex-1).add(fibList.get(lastIndex));
fibList.add(newFib);
checkFibo(i);
break;
default:
break;
}
return "IsNotFibo";
}
}
最佳答案
您的代码有两个问题:
情况1:不传递递归调用的返回值
属于默认实现的情况-1被完全忽略(即代码在处理了较大的输入后无法处理较小的输入)
这是一个工作代码:
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;
public class Solution {
public static ArrayList<BigInteger> fibList = new ArrayList<BigInteger>();
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
fibList.add(BigInteger.valueOf(0));
fibList.add(BigInteger.valueOf(1));
while(in.hasNextLine()) {
BigInteger nextBigDecimal = in.nextBigInteger();
System.out.println("input:" + nextBigDecimal);
System.out.println("isFibo: " + checkFibo(nextBigDecimal));
System.out.println(fibList);
}
}
public static boolean checkFibo(BigInteger i) {
int lastIndex = fibList.size() - 1;
int compareRes = i.compareTo(fibList.get(lastIndex));
System.out.println("Last fib num: " + fibList.get(lastIndex));
System.out.println("CompareRes: " + compareRes);
boolean isFibo = false;
switch(compareRes) {
case 0:
isFibo = true;
break;
case 1:
BigInteger newFib = fibList.get(lastIndex-1).add(fibList.get(lastIndex));
fibList.add(newFib);
isFibo = checkFibo(i);
break;
case -1:
isFibo = fibList.contains(i);
break;
}
return isFibo;
}
}
关于java - IsFibo没有返回期望的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29106634/