BigInteger、BigDecimal类的使用详解
我们都知道在java里边long算是存储长度比较大的了,但是如果有很大的数我们应该怎么处理呢,不用怕,java还为我们准备了一个BigInteger的类,那么这个类到底能存储多大的数呢,这个一时还真不好想,要取决于你计算机的内存大小,意味着我们的内存越大,这个类存储的位数就越大。接下来我们来看看BigInteger这个类。
BigInteger继承了Number类并且实现了Serializable , Comparable < BigInteger >接口
首先来看他的构造函数
这个类与之对应的还有三个常量,我们来看下
接下来我们说下他常用的构造函数
比较常用的就是用字符串来直接传入
BigInteger bigInteger = new BigInteger("999999999999999999");
比较常用的成员方法有如下:
BigInteger abs() 返回大整数的绝对值
BigInteger add(BigInteger val) 返回两个大整数的和
BigInteger and(BigInteger val) 返回两个大整数的按位与的结果
BigInteger andNot(BigInteger val) 返回两个大整数与非的结果
BigInteger divide(BigInteger val) 返回两个大整数的商
double doubleValue() 返回大整数的double类型的值
float floatValue() 返回大整数的float类型的值
BigInteger gcd(BigInteger val) 返回大整数的最大公约数
int intValue() 返回大整数的整型值
long longValue() 返回大整数的long型值
BigInteger max(BigInteger val) 返回两个大整数的最大者
BigInteger min(BigInteger val) 返回两个大整数的最小者
BigInteger mod(BigInteger val) 用当前大整数对val求模
BigInteger multiply(BigInteger val) 返回两个大整数的积
BigInteger negate() 返回当前大整数的相反数
BigInteger not() 返回当前大整数的非
BigInteger or(BigInteger val) 返回两个大整数的按位或
BigInteger pow(int exponent) 返回当前大整数的exponent次方
BigInteger remainder(BigInteger val) 返回当前大整数除以val的余数
BigInteger leftShift(int n) 将当前大整数左移n位后返回
BigInteger rightShift(int n) 将当前大整数右移n位后返回
BigInteger subtract(BigInteger val)返回两个大整数相减的结果
byte[] toByteArray(BigInteger val)将大整数转换成二进制反码保存在byte数组中
String toString() 将当前大整数转换成十进制的字符串形式
BigInteger xor(BigInteger val) 返回两个大整数的异或
我们来看几个测试
public static void main(String[] args) {
BigInteger b1 = new BigInteger("999999999999999999999");
BigInteger b2 = new BigInteger("888888888888888888888");
//加法
System.out.println(b1.subtract(b2));
//减法
System.out.println(b1.add(b2));
//乘法
System.out.println(b1.multiply(b2));
//除法
System.out.println(b1.divide(b2));
//取余
System.out.println(b1.remainder(b2));
//除并取余
BigInteger[] bbs = b1.divideAndRemainder(b2);
System.out.println(bbs[0]+"--"+bbs[1]);
}
程序的运行结果如下:
111111111111111111111
1888888888888888888887
888888888888888888887111111111111111111112
1
111111111111111111111
1--111111111111111111111
接下来我带大家看下BigInteger底层的源码
这个this是什么东西呢,我们继续往下看
/**
* Translates the String representation of a BigInteger in the
* specified radix into a BigInteger. The String representation
* consists of an optional minus or plus sign followed by a
* sequence of one or more digits in the specified radix. The
* character-to-digit mapping is provided by {@code
* Character.digit}. The String may not contain any extraneous
* characters (whitespace, for example).
*
* @param val String representation of BigInteger.
* @param radix radix to be used in interpreting {@code val}.
* @throws NumberFormatException {@code val} is not a valid representation
* of a BigInteger in the specified radix, or {@code radix} is
* outside the range from {@link Character#MIN_RADIX} to
* {@link Character#MAX_RADIX}, inclusive.
* @see Character#digit
*/
public BigInteger(String val, int radix) { //首先这里有一个基数因子 是指当前是多少进制的
int cursor = 0, numDigits;
final int len = val.length(); //这个地方会获取到当前传入字符串的总长度
//这里有两个常量 MIN_RADIX = 2 , MAX_RADIX = 36
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
throw new NumberFormatException("Radix out of range");
if (len == 0)
throw new NumberFormatException("Zero length BigInteger");
// Check for at most one leading sign
//这里会检测传入的字符串是否是纯数字
int sign = 1;
int index1 = val.lastIndexOf('-');
int index2 = val.lastIndexOf('+');
if (index1 >= 0) {
if (index1 != 0 || index2 >= 0) {
throw new NumberFormatException("Illegal embedded sign character");
}
sign = -1;
cursor = 1;
} else if (index2 >= 0) {
if (index2 != 0) {
throw new NumberFormatException("Illegal embedded sign character");
}
cursor = 1;
}
if (cursor == len)
throw new NumberFormatException("Zero length BigInteger");
// Skip leading zeros and compute number of digits in magnitude
while (cursor < len &&
Character.digit(val.charAt(cursor), radix) == 0) {
cursor++;
}
if (cursor == len) {
signum = 0;
mag = ZERO.mag;
return;
}
numDigits = len - cursor;
signum = sign;
// Pre-allocate array of expected size. May be too large but can
// never be too small. Typically exact.
long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1;
if (numBits + 31 >= (1L << 32)) {
reportOverflow();
}
int numWords = (int) (numBits + 31) >>> 5;
int[] magnitude = new int[numWords];
// Process first (potentially short) digit group
int firstGroupLen = numDigits % digitsPerInt[radix];
if (firstGroupLen == 0)
firstGroupLen = digitsPerInt[radix];
String group = val.substring(cursor, cursor += firstGroupLen);
magnitude[numWords - 1] = Integer.parseInt(group, radix);
if (magnitude[numWords - 1] < 0)
throw new NumberFormatException("Illegal digit");
// Process remaining digit groups
int superRadix = intRadix[radix];
int groupVal = 0;
while (cursor < len) {
group = val.substring(cursor, cursor += digitsPerInt[radix]);
groupVal = Integer.parseInt(group, radix);
if (groupVal < 0)
throw new NumberFormatException("Illegal digit");
destructiveMulAdd(magnitude, superRadix, groupVal);
}
// Required for cases where the array was overallocated.
mag = trustedStripLeadingZeroInts(magnitude);
if (mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
}
看了以上的代码,相信你对BigInteger大概已经有了一个新的认识。
以上内容部分来自网络,与BigInteger对应的还有一个BigDecimal,可以存小数,与BigInteger的用法一模一样,有问题可以在下面评论,技术问题可以私聊我。
BigInteger、BigDecimal类的使用详解的更多相关文章
- 【转】UML类图与类的关系详解
UML类图与类的关系详解 2011-04-21 来源:网络 在画类图的时候,理清类和类之间的关系是重点.类的关系有泛化(Generalization).实现(Realization).依赖(D ...
- String类的构造方法详解
package StringDemo; //String类的构造方法详解 //方法一:String(); //方法二:String(byte[] bytes) //方法三:String (byte[] ...
- [转]c++类的构造函数详解
c++构造函数的知识在各种c++教材上已有介绍,不过初学者往往不太注意观察和总结其中各种构造函数的特点和用法,故在此我根据自己的c++编程经验总结了一下c++中各种构造函数的特点,并附上例子,希望对初 ...
- Scala 深入浅出实战经典 第63讲:Scala中隐式类代码实战详解
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...
- UML类图与类的关系详解
摘自:http://www.uml.org.cn/oobject/201104212.asp UML类图与类的关系详解 2011-04-21 来源:网络 在画类图的时候,理清类和类之间的关系是重点.类 ...
- phpcms加载系统类与加载应用类之区别详解
<?php 1. 加载系统类方法load_sys_class($classname, $path = ''", $initialize = 1)系统类文件所在的文件路径:/phpcms ...
- c++类的构造函数详解
c++类的构造函数详解 一. 构造函数是干什么的 class Counter{ public: // 类Counter的构造函数 // 特点:以类名作为函数名,无返回类 ...
- 对python3中pathlib库的Path类的使用详解
原文连接 https://www.jb51.net/article/148789.htm 1.调用库 ? 1 from pathlib import 2.创建Path对象 ? 1 2 3 4 5 ...
- String类内存空间详解
java.lang.String类内存问题详解 字符串理解的难点在于其在堆内存空间上的特殊性,字符串String对象在堆内存上有两种空间: 字符串池(String pool):特殊的堆内存,专门存放S ...
随机推荐
- Gym - 101670E Forest Picture (CTU Open Contest 2017 模拟)
题目: https://cn.vjudge.net/problem/1451310/origin 题意&思路: 纯粹模拟. 大体题意是这样的: 1.有人要在一个10-9<=x<=1 ...
- PAT 1138 Postorder Traversal
Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and in ...
- RequestMapping注解_修饰类
[使用RequestMapping映射请求] 1.Spring MVC使用 @RequestMapping 注解为控制器指定可以处理哪些URL请求. 2.在控制器的类定义及方法定义处都可以标注. @R ...
- 关于Scrum 实战故事录播的感悟升级
昨晚与几位自组织的伙伴进行了<Scrum 实战> 第17 章 <富有成效的每日站会>录播Sprint 不断的优化和精进的感悟. 首先,D兄给予了如下的建议: 1. 将段落 分得 ...
- mysql执行show processlist unauthenticated user 解决方法
一台unibilling机器前几天突然负载变重. 在top中发现cpu被大量占用. agi程序运行的很慢,并出现僵尸进程. 其实当时只有50个左右的并发呼叫. 远远达不到正常水准. 重新启动机器问题也 ...
- [luoguP2486] [SDOI2011]染色(树链剖分)
传送门 就是个模板啦 记录每一个点的左端点颜色和右端点颜色和当前端点颜色段数. 合并时如果左孩子右端点和右孩子左端点不同就 ans-- 在重链上跳的时候别忘记统计一下 ——代码 #include &l ...
- vue.js编程式路由导航 --- 由浅入深
编程式路由导航 实例中定义一个方法,这个方法绑定在标签上 然后就设置路由跳转 语法 this.$router.history.push('要跳转路由的地址') <!DOCTYPE html> ...
- A+B Problem IV
描述acmj最近发现在使用计算器计算高精度的大数加法时很不方便,于是他想着能不能写个程序把这个问题给解决了. 输入 包含多组测试数据每组数据包含两个正数A,B(可能为小数且位数不大于400) 输出 ...
- MySQL慢日志切割邮件发送脚本
#!/bin/bashtime=`date -d yesterday +"%Y-%m-%d"`slowlog='/usr/local/percona/data/slow.log'# ...
- 为什么Linux下的环境变量要用大写而不是小写
境变量的名称通常用大写字母来定义.实际上用小写字母来定义环境变量也不会报错,只是习惯上都是用大写字母来表示的. 首先说明一下,在Windows下是不区分大小写的,所以在Windows下怎么写都能获取到 ...