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

nba*_*lle 3 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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Gui*_*ume 9

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


小智 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));
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 应该使用BigInteger.valueOf(long)而不是转换为String然后转换为BigInteger. (5认同)