本文介绍了如何对无法存储在一个变量中的大数字进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Java, I would like to be able to do operations on really big integers (that can't be stored in a long), how can I do that?

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

What is the best way to deal with this, with good performances? Should I create my own data type that contains several long variables?

示例:

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;
}

谢谢!

推荐答案

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

}

这篇关于如何对无法存储在一个变量中的大数字进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 09:47