问题描述
我目前正在尝试解决一个 HackerRank 问题,这个问题被称为 Fibonacci Modified。
该方法返回一个 int 但预计我将获得巨大的值。我正在用 Java 解决这个问题。
这是我的代码
static int fibonacciModified(int t1,int t2,int n) {
BigInteger[] f = new BigInteger[n];
f[0] = BigInteger.ZERO;
f[1] = BigInteger.ONE;
BigInteger value = BigInteger.ONE;
for(int i = 2; i < n; i++) {
f[i] = f[i-1].multiply(f[i-1]).add(f[i-2]);
value = f[i];
}
return value.intValue();
}
当 t1 = 0、t2 = 1、n = 10 时,我的测试用例失败了。我的输出是 -1022889632。 正确答案是 84266613096281243382112。如果我将方法更改为返回 BigInteger,那么我确实得到了正确答案。
编辑:这是问题的链接https://www.hackerrank.com/challenges/fibonacci-modified/problem
解决方法
你不能,the maximum value for int 是 2,147,483,647
(32 位值)。如果您需要大数字,则必须使用适当的变量类型。
如果由于某种原因你想完全避免 BigInteger
并且你以后不打算做任何算术运算,你总是可以返回一个 String
关于the hackerrank problem,只需将结果变量类型修改为BigInteger
。实际上,他们似乎意识到 32/64 位问题……他们正在使用 String
值来防止它。
没有理由保留整个代码模板结构。他们只关心输入/输出。您可以修改除这两件事之外的所有内容。