Java中BigInteger的各种方法详解

顾名思义,BigInteger就是用于处理题目中涉及到大整数的加减乘除运算。

·int 与 BigInteger之间的相互转化

import java.math.BigInteger;
public class Demo1{
    public static void main(String[] args){
        //int 与 BigInteger之间的正确转换方法:
        //int 转换为 BigInteger的方法:
        int p = 1;
        BigInteger a = BigInteger.valueOf(p);
        //BigInteger 转换为 int的方法:
        BigInteger d = new BigInteger("9");
        int temp = d.intValue();*/
    }
}

·错误案例:BigInteger 与 int 之间不能直接相互转化

import java.math.BigInteger;
public class Demo2{
    public static void main(String[] args){
        BigInteger temp = new BigInteger("9");
        int a = 1;
        System.out.println(temp+a);
    }
}

·BigInteger的常用方法

import java.math.BigInteger;
public class Demo3{
    public static void main(String[] args){
        //常用方法:
        BigInteger temp = new BigInteger("9");
        BigInteger temp1 = new BigInteger("6");
        BigInteger temp2 = new BigInteger("-6");
        //add();-------加法
        System.out.println(temp.add(temp1));
        //subtract();-------减法
        System.out.println(temp.subtract(temp1));
        //multiply()-------乘法
        System.out.println(temp.multiply(temp1));
        //divide()-------相除取整
        System.out.println(temp.divide(temp1));
        //remainder()与mod()-------取余
        System.out.println(temp.remainder(temp1));
        System.out.println(temp.mod(temp1));
        //negate()------取相反数
        System.out.println(temp.negate());
        //abs()------取绝对值
        System.out.println(temp2.abs());
        //min(),max()------取最大与最小值
        System.out.println(temp1.min(temp2));
        System.out.println(temp1.max(temp2));
        //gcd()------取最大公约数
        System.out.println(temp1.gcd(temp));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值