如何对无法存储在一个变量中的大数字进行操作

时间:2010-12-17 17:18:58

标签: java integer

在Java中,我希望能够对非常大的整数进行操作(不能长时间存储),我该怎么做?

有什么最好的方法可以解决这个问题,表现如何?我应该创建自己的包含几个长变量的数据类型吗?

示例:

public class MyBigInteger{
    private long firstPart;
    private long secondPart;

   ...
}

public MyBigInteger add(long a, long b){
    MyBigInteger res;

    // WHAT CAN I DO HERE, I guess I could do something with the >> << operators, but I've never used them!

    return res;
}

谢谢!

5 个答案:

答案 0 :(得分:9)

您应该检查BigInteger java类。它完全符合您的需求。

答案 1 :(得分:6)

import java.math.BigInteger;

public class BigIntegerTest {

    public BigInteger add(long a, long b){
        BigInteger big1 = new BigInteger(Long.toString(a));
        BigInteger big2 = new BigInteger(Long.toString(b));

        return big1.add(big2);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new BigIntegerTest().add(22342342424323423L, 234234234234234234L));
    }

}

答案 2 :(得分:4)

您是否考虑过标准库类java.math.BigInteger,它支持任意精度的整数?

答案 3 :(得分:1)

如果你真的需要高性能,BigInteger / BigDecimal不会削减它。我使用了apfloat库,对我来说非常好。

答案 4 :(得分:0)

如果数字真的很长,我会建议将它们存储在一个链表(每个节点一个数字)或一个文件(在这种情况下,io访问延迟将在那里)然后做一个数字加法我们曾经在我们的二年级手工做。