如果BigInteger对于int太大,如何返回int?
我目前正试图解决一个黑客问题,这个问题叫做Fibonacci修正
该方法返回一个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。 正确答案是8426661309621243382112。如果我更改方法以返回一个BigInteger,那么我确实得到了正确的答案
编辑:这是指向问题https://www.hackerrank.com/challenges/fibonacci-modified/problem的链接
# 1 楼答案
不能将the maximum value for int设为
2,147,483,647
(32位值)。如果需要大的数字,则必须使用适当的变量类型如果出于某种原因,您希望完全避免
BigInteger
,并且以后不打算进行任何算术运算,那么您可以始终返回String
关于the hackerrank problem,只需将结果变量类型修改为
BigInteger
。实际上,他们似乎意识到32/64位的问题。。。他们正在使用String
值来阻止它。没有理由保留整个代码模板结构。他们只关心输入/输出。您可以修改除这两项之外的所有内容
这是他们的输入:
这是他们的输出(在这里您可以看到他们的输出预期为^{):