算法篇——高精度(Java)

我们知道c/c++中的高精度运算都需要用数组保存每一位的数,然后对数组进行运算。实现起来很麻烦。

但我们的大Java中有专门针对高精度的类库,即BigInteger() BigDecimal()。下面介绍两者的区别以及常用的方法。

区别: BigInteger()不能进行小数的运算,即只能进行整数的运算。而BigDecimal()则可以进行小数的运算。

常用方法:

BigInteger():

BigInteger类型的数可以用scanner.nextBigInteger()读入。

也可以使用静态的valueOf()方法将普通的数转为BigInteger类型的数。

也可以直接使用构造器new BigInteger(String str)将str转为BIgInteger类型的数。

常用方法列表:

BigInteger add(BigInteger other) 返回两个大整数的和
BigInteger subtract(BigInteger other) 返回两个大整数的差 
BigInteger multiply(BigInteger other) 返回两个大整数的积
BigInteger divide(BigInteger other) 返回两个大整数的商
BigInteger mod(BigInteger other) 返回两个大整数的余数
BigInteger sqrt(BigInteger other) 返回这个大整数的平方根
int compareTo(BigInteger other)

如果两个大整数相等,返回0;如果大整数小于other,返回负数;否则返回正数。

BigDecimal():

BigDecimal类型的数可以用scanner.nextBigDecimal()读入。

也可以使用静态的valueOf()方法将普通的数转为BigDecimal类型的数。

也可以直接使用构造器new BigDecimal(String str)将str转为BigDecimal类型的数。

常用方法列表:

BigDecimal add(BigInteger other) 返回两个大整数的和
BigDecimal subtract(BigInteger other) 返回两个大整数的差 
BigDecimal multiply(BigInteger other) 返回两个大整数的积
BigDecimal divide(BigInteger other) 返回两个大整数的商
BigDecimal divide(BigInteger other,RoundingMode mode) 如果商是个无限循环小数,第一个divide方法会抛出一个异常,要得到四舍五入的结果就要使用第二个方法,RoundingMode.HALE_UP是常用的四舍五入方式。
int compareTo(BigInteger other)

如果两个大整数相等,返回0;如果大整数小于other,返回负数;否则返回正数。

static BigDecimal valueOf(long x,int scale) 返回值等于x或x/10^scale的一个大实数

以上就是Java中的大整数处理。(方法不全,只包含常用方法)。

你可能感兴趣的:(java,算法)