shu*_*vro 4 java stack-overflow recursion biginteger
为什么此Java代码会引发StackOverflowError异常?
public class factorial2 {
public BigInteger fact( BigInteger n)
{
BigInteger one = new BigInteger("1");
if(n.equals("0"))
return one;
else
return n.multiply(fact(n.subtract(one)));
}
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
factorial2 f = new factorial2();
for(int i=0;i<n;i++)
{
BigInteger b = sc.nextBigInteger();
System.out.println(f.fact(b));
}
sc.close();
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用生成阶乘BigInteger。但是,为什么我的代码在输入时给出引用异常?
问题在于您的基本情况;n(是BigInteger)将不等于"0"(是String)。因此,您继续进行else重复的块。此外,BigInteger还包含的常量ONE,ZERO因此您可以编写类似
public static BigInteger fact(BigInteger n) {
if (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE))
return BigInteger.ONE;
else
return n.multiply(fact(n.subtract(BigInteger.ONE)));
}
Run Code Online (Sandbox Code Playgroud)
或 使用三元运算(条件运算符? :)
public static BigInteger fact(BigInteger n) {
return (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE)) ? BigInteger.ONE
: n.multiply(fact(n.subtract(BigInteger.ONE)));
}
Run Code Online (Sandbox Code Playgroud)