每日编程(21)

一个超级好用的数据类型(BigInteger)

在这里插入图片描述

下面是我的例子(PAT乙级1017的简单做法,非常厉害)

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        BigInteger a = in.nextBigInteger();
        int b = in.nextInt();
        System.out.println(a.divide(BigInteger.valueOf(b)) + " " + a.mod(BigInteger.valueOf(b)));


        //关于BigInteger的一些基本操作
        //加法
        BigInteger c = a.add(BigInteger.valueOf(767889778));
        System.out.println("加法操作:" + c);
        //乘法
        BigInteger d = a.multiply(BigInteger.valueOf(767889778));
        System.out.println("乘法操作:" + d);
        //减法
        BigInteger e = a.subtract(BigInteger.valueOf(767889778));
        System.out.println("减法操作:" + e);
        //除法
        BigInteger f = a.divide(BigInteger.valueOf(767889778));
        System.out.println("除法操作:" + f);
        //取余
        BigInteger g = a.mod(BigInteger.valueOf(767889778));
        System.out.println("取余运算:" + g);
        //比较
        int h = a.compareTo(BigInteger.valueOf(76789778));
        System.out.println(h);

    }
}

说明:

1.这种大整数的操作特别在算法竞赛中非常适用,简化许多操作,不用模拟竖式计算的过程,减去数据类型之间的转化。
2.计算精度不会丢失。

猜你喜欢

转载自blog.csdn.net/qq_41033299/article/details/89164383