这是我想到的IsFibo HackerRank问题的解决方案。 (https://www.hackerrank.com/challenges/is-fibo)。我想知道为什么它不会返回“IsFibo”为5.我的逻辑可能是错误的,如果有人指出我的错误,我会很感激。这是代码:
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";
}
}
答案 0 :(得分: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;
}
}