加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:22:50 所属栏目:Java 来源:网络整理
导读:在 Java中,我希望能够对非常大的整数进行操作(不能长时间存储),我该怎么做? 有良好表现的最佳方法是什么?我应该创建自己的包含几个长变量的数据类型吗? 例: public class MyBigInteger{ private long firstPart; private long secondPart; ...}public My
在 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;
}

谢谢!

解决方法

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

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读