Java 中可以使用两种方式存储大整数:
一、使用 BigInteger 类:BigInteger 类可以存储任意大小的整数,它提供了大量的方法进行整数运算。可以使用 BigInteger 的构造函数来创建一个 BigInteger 对象,例如:
import java.math.BigInteger;
public class BigIntegerExample {
public static void main(String[] args) {
BigInteger bigInteger1 = new BigInteger("12345678901234567890");
BigInteger bigInteger2 = BigInteger.valueOf(9876543210L);
BigInteger sum = bigInteger1.add(bigInteger2);
System.out.println("Sum: " + sum);
}
}
BigInteger
是 Java 中用于存储任意大小整数的类,它提供了丰富的方法来进行整数运算。下面是 BigInteger 常用方法的介绍:
- 构造函数
BigInteger(String val)
:使用十进制字符串 val 来构造一个 BigInteger 对象。BigInteger(String val, int radix)
:使用基数 radix 和字符串 val 来构造一个 BigInteger 对象。 - 基本运算方法
add(BigInteger val)
:返回当前 BigInteger 对象加上 val 后的结果。subtract(BigInteger val)
:返回当前 BigInteger 对象减去 val 后的结果。multiply(BigInteger val)
:返回当前 BigInteger 对象乘以 val 后的结果。divide(BigInteger val)
:返回当前 BigInteger 对象除以 val 后的结果。mod(BigInteger val)
:返回当前 BigInteger 对象除以 val 后的余数。pow(int exponent)
:返回当前 BigInteger 对象的 exponent 次幂。 - 比较方法
compareTo(BigInteger val)
:比较当前 BigInteger 对象和 val 的大小关系,返回 -1、0、1 分别表示小于、等于、大于。equals(Object x)
:判断当前 BigInteger 对象是否与 x 相等,如果相等返回 true,否则返回 false。 - 转换方法
byteValue()
:返回当前 BigInteger 对象转换为 byte 类型后的值。shortValue()
:返回当前 BigInteger 对象转换为 short 类型后的值。intValue()
:返回当前 BigInteger 对象转换为 int 类型后的值。longValue()
:返回当前 BigInteger 对象转换为 long 类型后的值。floatValue()
:返回当前 BigInteger 对象转换为 float 类型后的值。doubleValue()
:返回当前 BigInteger 对象转换为 double 类型后的值。toString()
:返回当前 BigInteger 对象的十进制字符串表示形式。
以上是 BigInteger 常用的方法介绍,除此之外,BigInteger 还提供了很多其他方法,如位运算方法、求最大公约数和最小公倍数的方法等。
二、使用字符串:可以将大整数转换成字符串,然后进行运算。例如:
public class StringExample {
public static void main(String[] args) {
String num1 = "12345678901234567890";
String num2 = "9876543210";
String sum = addStrings(num1, num2);
System.out.println("Sum: " + sum);
}
public static String addStrings(String num1, String num2) {
StringBuilder result = new StringBuilder();
int carry = 0, i = num1.length() - 1, j = num2.length() - 1;
while (i >= 0 || j >= 0 || carry > 0) {
int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
int sum = n1 + n2 + carry;
carry = sum / 10;
result.append(sum % 10);
i--;
j--;
}
return result.reverse().toString();
}
}
这里使用了一个 addStrings 方法来实现两个字符串的相加,该方法使用了 StringBuilder 来构造结果字符串,并且按照相加的逻辑进行循环处理,最终返回结果字符串。需要注意的是,在字符串相加时需要将每个字符转换成数字进行运算。