java.math.BigInteger的使用

本文介绍Java中如何使用BigInteger类处理超过long型的最大整数,包括加、减、乘、除等运算方法,并提供实例说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java中long型为最大整数类型,对于超过long型的数据如何去表示呢.在Java的世界中,超过long型的整数已经不能被称为整数了,它们被封装成BigInteger对象.在BigInteger类中,实现四则运算都是方法来实现,并不是采用运算符.

  BigInteger类的构造方法:

 BigInteger b = new BigInteger(str);     //构造方法中,采用字符串的形式给出整数

        BigInteger big1 = new BigInteger("12345678909876543210");

        BigInteger big2 = new BigInteger("98765432101234567890");

        //add实现加法运算
        BigInteger bigAdd = big1.add(big2);
        
        //subtract实现减法运算
        BigInteger bigSub = big1.subtract(big2);

        //multiply实现乘法运算
        BigInteger bigMul = big1.multiply(big2);

        //divide实现除法运算
        BigInteger bigDiv = big2.divide(big1);

        System.out.println(bigAdd);
        System.out.println(bigSub);
        System.out.println(bigMul);
        System.out.println(bigDiv);

        /**
         * 111111111011111111100
         * -86419753191358024680
         * 1219326312117055326552354825111263526900
         * 8
         */
/**
构造一个十进制的BigInteger对象,
该构造方法可以发生NumberFormatException异常,
也就是说,字符串参数VAL中如果含有非数字字符就会发生NumberFormatException异常。
*/
public BigInteger(String VAL)
BigInteger类的常用方法:

public BigInteger add(BigInteger val)   返回当前大整数对象与参数指定的大整数对象的和

public BigInteger subtract(BigInteger val)  返回当前大整数对象与参数指定的大整数对象的差

public BigInteger multiply(BigInteger val)   返回当前大整数对象与参数指定的大整数对象的积

public BigInteger devide(BigInteger val)    返回当前大整数对象与参数指定的大整数对象的商

public BigInteger remainder(BigInteger val)    返回当前大整数对象与参数指定的大整数对象的余

public int compareTo(BigInteger val)    返回当前大整数对象与参数指定的大整数对象的比较结果,返回值是1、-1、0,分别表示当前大整数对象大于、小于或等于参数指定的大整数。

public BigInteger abs()    返回当前大整数对象的绝对值

public BigInteger pow(int exponent)   返回当前大整数对象的exponent次幂。

public String toString()    返回当前当前大整数对象十进制的字符串表示。

public String toString(int p)   返回当前大整数对象p进制的字符串表示。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值