编写程序实现两个超长正整数(每个最长80位数字)的减法运算。用java编写
时间: 2023-11-26 11:04:45 浏览: 77
以下是 Java 代码实现:
```java
import java.util.Scanner;
public class LongIntSubtraction {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
String num1 = sc.nextLine();
System.out.print("Enter the second number: ");
String num2 = sc.nextLine();
int[] result = subtract(num1, num2);
System.out.print("Result: ");
for (int i = result.length - 1; i >= 0; i--) {
System.out.print(result[i]);
}
}
public static int[] subtract(String num1, String num2) {
int[] result = new int[80];
int index = 79;
int carry = 0;
for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--) {
int n1 = (i >= 0) ? num1.charAt(i) - '0' : 0;
int n2 = (j >= 0) ? num2.charAt(j) - '0' : 0;
int diff = n1 - n2 - carry;
if (diff < 0) {
diff += 10;
carry = 1;
} else {
carry = 0;
}
result[index--] = diff;
}
while (index >= 0 && result[index] == 0) {
index--;
}
if (index == -1) {
return new int[] { 0 };
}
int[] res = new int[index + 1];
for (int i = 0; i <= index; i++) {
res[i] = result[i];
}
return res;
}
}
```
该代码使用数组实现超长正整数的减法运算,支持任意长度的数字。它从最低位开始相减,如果结果小于0,则借位1,否则不借位。最后,需要去掉结果数组中前导的0,并且如果结果为0,则返回一个长度为1的数组。
阅读全文