以下是 Java 中两个长整数相加的实现代码:
java
import java.math.BigInteger;
import java.util.Scanner;
public class BigIntegerAddition {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first long integer: ");
String num1 = scanner.nextLine();
System.out.print("Enter the second long integer: ");
String num2 = scanner.nextLine();
BigInteger bigInt1 = new BigInteger(num1);
BigInteger bigInt2 = new BigInteger(num2);
BigInteger result = bigInt1.add(bigInt2);
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + result);
}
}
这个程序使用 Java 中的 `BigInteger` 类来表示和操作两个非常大的整数。
这里是程序的工作流程:
1. 使用 `Scanner` 类从用户那里获取两个长整数。
2. 使用 `BigInteger` 类创建两个 `BigInteger` 对象来表示这两个长整数。
3. 使用 `BigInteger` 对象的 `add()` 方法来计算这两个大整数的和。
4. 将结果输出到控制台。
使用 `BigInteger` 类可以轻松地处理超出基本数据类型范围的整数。它提供了一系列的算术运算方法,如加法、减法、乘法和除法。这个例子展示了如何使用 `BigInteger` 类来实现两个长整数的相加操作。
查看详情
查看详情