如果 BigInteger 对于 int 来说太大了,如何 return int?

How to return int if BigInteger is too big for int?

我目前正在尝试解决 HackerRank 问题,所讨论的问题称为 Fibonacci Modified。

方法 return 是一个整数,但预计我将获得巨大的价值。我正在 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。如果我将方法更改为 return a BigInteger,那么我会得到正确答案。

编辑:这是 link 问题 https://www.hackerrank.com/challenges/fibonacci-modified/problem

你不能,the maximum value for int2,147,483,647(32 位值)。如果您需要大数字,则必须使用适当的变量类型。

如果出于某种原因你想完全避免 BigInteger 并且以后不打算进行任何算术运算,你总是可以 return a String


关于the hackerrank problem,只需将结果变量类型修改为BigInteger即可。实际上,他们似乎意识到 32/64 位问题...他们正在使用 String 值来防止它。

没有理由保留整个代码模板结构。他们只关心input/output。除了这两件事,您可以修改所有内容。

这是他们的输入

这是他们的输出(在这里你可以看到他们的输出预计是String):