Java BigInteger的使用

Java BigInteger的使用

特点

BigInteger支持任意精度的整数运算(范围为无穷大)

方法

  1. 读入一个BigInteger

    Scanner scanner = new Scanner(System.in);
    //读入一个Int作为对比
    int example_int = scanner.nextInt();
    //读入一个BigInteger
    BigInteger bigInteger = scanner.nextBigInteger();
    
    
  2. 构造一个BigInteger

    //把 radix 进制的字符串 构造为 BigInteger
    String str = "101110011101001001";
    int radix = 2;
    BigInteger bigInt = new BigInteger(str,radix);  //一个二进制数的转化
    
    //如果没有radix 参数,则默认转化为十进制
    BigInteger bigInt2 = new BigInteger("124124813579235");
    
  3. 基本运算

    BigInteger a = new BigInteger("123");
    BigInteger b = new BigInteger("3124");
    int n = 3;
    //加运算 : add
    BigInteger outcome_add = a.add(b);
    //减运算 : subtract
    BigInteger outcome_subtract = a.subtract(b);
    //乘运算 : multiply
    BigInteger outcome_multiply = a.multiply(b);
    //除运算 : divide
    BigInteger outcome_divide = a.divide(b);
    //取模运算;mod
    BigInteger outcome_mod = a.mod(b);
    //求余运算 : remainder
    BigInteger outcome_remainder = a.remainder(b);
    //次方运算 : pow
    BigInteger outcome_pow = a.pow(n);
    //取绝对值 :abs
    BigInteger outcome_abs = a.abs();
    //取相反数 :negate
    BigInteger outcome_negate = a.negate();
    //大小比较
    //1.compareTo() :返回int  1 大于 0 等于 -1 小于
    int outcome = a.compareTo(b);
    //2.max()返回较大值
    int outcome1 = a.max(b);
    //3.min()返回较小值
    int outcome2 = a.min(b);
    
  4. 类型转化

    BinInteger bigNum = new BigInteger("1232141241");
    //二进制补码转换
    byte[] num1 = bigNum.toByteArray();
    //十进制字符串转换
    String num2 = bigNum.toString();
    //radix进制字符串转化(默认为十进制)
    int radix = 8; //八进制
    String num3 = bigNum.toString(radix);
    //int转换
    int num4 = bigNum.intValue();
    //long转换
    int num5 = bigNum.longValue();
    //float转换
    int num6 = bigNum.floatValue();
    //double转换
    int num7 = bigNum.doubleValue();
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值