Java BigInteger的.equals()方法工作不正常
所以最近,我尝试用斐波那契序列来研究动态规划。大整数 不管我输入多少,它都会溢出。 即使是我真的不明白的1 所以从我所看到的来看,第18-20行似乎出于某种原因没有运行 我甚至尝试让它在if条件中抛出一个RuntimeException,但是程序从来不会因为RuntimeException而崩溃。它总是从StackOverflowerr崩溃,这意味着第18-20行从未运行过。这也意味着我总是会有一个StackOverflower错误,因为我的递归永远不会结束 我做错了什么Java BigInteger的.equals()方法工作不正常,java,Java,所以最近,我尝试用斐波那契序列来研究动态规划。大整数 不管我输入多少,它都会溢出。 即使是我真的不明白的1 所以从我所看到的来看,第18-20行似乎出于某种原因没有运行 我甚至尝试让它在if条件中抛出一个RuntimeException,但是程序从来不会因为RuntimeException而崩溃。它总是从StackOverflowerr崩溃,这意味着第18-20行从未运行过。这也意味着我总是会有一个StackOverflower错误,因为我的递归永远不会结束 我做错了什么 package cos
package cos.view;
import java.math.BigInteger;
import java.util.HashMap;
public class Fibonacci {
static BigInteger one = new BigInteger("1");
static BigInteger two = new BigInteger("2");
static BigInteger three = new BigInteger("3");
static BigInteger testNumber = new BigInteger("5");
static HashMap<BigInteger, BigInteger> map = new HashMap<BigInteger, BigInteger>();
public static void main(String[] args) {
System.out.println(fibonacci(testNumber, map));
}
public static BigInteger fibonacci(BigInteger n, HashMap<BigInteger, BigInteger> map) {
if (n.equals(0) || n.equals(1)) {
return n;
}
if (map.containsKey(n)) {
return map.get(n);
}
map.put(n.subtract(one), fibonacci(n.subtract(one), map));
map.put(n.subtract(two), fibonacci(n.subtract(two), map));
BigInteger nMinusOne = map.get(n.subtract(one));
BigInteger nMinusTwo = map.get(n.subtract(two));
BigInteger sumValue = nMinusOne.add(nMinusTwo);
map.put(n, sumValue);
return sumValue;
}
}
比较BigInteger和int将始终为false,因为它们不是相同的类型
您需要比较两个BigInteger:
比较BigInteger和int将始终为false,因为它们不是相同的类型
您需要比较两个BigInteger:
查看文档以了解更多信息 返回: 当且仅当指定对象是数值等于此BigInteger的BigInteger时,为true 更改比较元素的方式:
查看文档以了解更多信息 返回: 当且仅当指定对象是数值等于此BigInteger的BigInteger时,为true 更改比较元素的方式:
if(n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE)){
return n;
}
if(n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE)){
return n;
}