在 Java 中,基本数据类型的整数有固定取值范围:int、long 容量有限,一旦超出最大值就会发生数值溢出,且编译运行不会报错,导致业务数据错乱。

为解决超大整数运算问题,Java 提供了 BigInteger 类(位于 java.math 包),专门用于任意长度的超大整数运算,完美支持无限长度整数的加减乘除、取模、幂运算、位运算、进制转换等操作,是算法竞赛、金融统计、密码学、大数加密场景的核心类。
一旦数值超过 long 最大值,基本类型完全无法存储,且溢出静默失效(无报错、结果错误)。
此时必须使用 BigInteger。
+ - * / % 运算符,必须调用专属方法运算BigInteger 没有无参构造,必须通过指定数值、字符串、进制、数组创建对象。
// 通过 long 数值创建(适合 long 范围内数值)BigInteger num1 = BigInteger.valueOf(123456);// 负数创建BigInteger num2 = BigInteger.valueOf(-98765);
唯一可以直接定义超出 long 范围超大整数的方式,开发首选。
// 远超 long 最大值的超大整数BigInteger bigNum = new BigInteger("999999999999999999999999999999");可将指定进制的数字字符串转为十进制 BigInteger。
// 将二进制 1010 转为十进制数字BigInteger binaryNum = new BigInteger("1010", 2);// 将十六进制转为十进制BigInteger hexNum = new BigInteger("FF", 16);内置常用常量,无需 new 对象,节省内存:
BigInteger.ZERO; // 0BigInteger.ONE; // 1BigInteger.TWO; // 2BigInteger.TEN; // 10
所有运算原对象不变,返回新对象,必须接收返回值。
BigInteger a = new BigInteger("100000000000000000000");BigInteger b = new BigInteger("200000000000000000000");// 1. 加法BigInteger addRes = a.add(b);// 2. 减法BigInteger subRes = a.subtract(b);// 3. 乘法BigInteger mulRes = a.multiply(b);// 4. 除法(整除,只取整数部分)BigInteger divRes = b.divide(a);// 5. 取模BigInteger modRes = b.mod(a);// 6. 求绝对值BigInteger absRes = subRes.abs();// 7. 取反BigInteger negRes = a.negate();// 8. 幂运算BigInteger powRes = a.pow(3);// 9. 最大/最小值BigInteger maxRes = a.max(b);BigInteger minRes = a.min(b);普通 divide 只返回商,divideAndRemainder 可同时获取商和余数,算法高频使用。
BigInteger num = new BigInteger("100");BigInteger divisor = new BigInteger("3");// 数组:[0]商,[1]余数BigInteger[] res = num.divideAndRemainder(divisor);System.out.println("商:" + res[0]);System.out.println("余数:" + res[1]);禁止使用 > < == 比较 BigInteger 对象,必须使用专属比较方法。
BigInteger x = new BigInteger("888");BigInteger y = new BigInteger("666");// compareTo:大于返回1,等于返回0,小于返回-1int cmp = x.compareTo(y);// 判断是否相等(推荐,杜绝 == 地址比较坑)boolean eq = x.equals(y);// 判断正负、零boolean zero = x.equals(BigInteger.ZERO);boolean positive = x.compareTo(BigInteger.ZERO) > 0;boolean negative = x.compareTo(BigInteger.ZERO) < 0;BigInteger num = new BigInteger("255");String binary = num.toString(2); // 转二进制String oct = num.toString(8); // 转八进制String hex = num.toString(16); // 转十六进制注意:超出基本类型范围会抛异常,转换前需判断范围。
// 转 long(范围溢出抛异常)long longVal = num.longValue();// 转 intint intVal = num.intValue();// 精准判断是否可以转为 longboolean canLong = num.bitLength() <= 63;
BigInteger n = new BigInteger("10");n.and(BigInteger.ONE); // 与运算n.or(BigInteger.ZERO); // 或运算n.xor(BigInteger.TWO); // 异或运算n.not(); // 取反n.shiftLeft(2); // 左移(乘2^2)n.shiftRight(1); // 右移(除2)// 获取二进制位数int bitLen = n.bitLength();// 判断是否为素数boolean prime = n.isProbablePrime(50); // 参数为置信度所有运算不改变原对象,不接收返回值等于白算。
// 错误写法BigInteger a = BigInteger.TEN;a.add(BigInteger.TEN);System.out.println(a); // 仍然是10// 正确写法a = a.add(BigInteger.TEN);
== 比较对象地址,equals 比较数值内容,必须用 equals / compareTo。
BigInteger 是对象,不支持 + - * /,编译直接报错,必须调用方法。
超出 long 范围的数值,不能用 valueOf/数字直接赋值,只能用字符串构造。