第一种:
解题思路: 使用java中自带的BigInteger类型进行加减
注意事项: 前头一定要记得import java.math.BigInteger;
参考代码:
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger A = scanner.nextBigInteger();
BigInteger B = scanner.nextBigInteger();
BigInteger SUM = A.add(B); //两个BigInteger类型的数据的加法用add()方法
System.out.println(SUM);
}
}
第二种:(我是先用的第二种方法,但是写完之后提交总是显示答案错误45,所以如果有各路大神看出来请指点下,感激不尽!!!)
解题思路: 使用字符数组char[] 从后往前逐个相加,相加大于或等于10一定要记得进位
参考代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {Scanner scanner = new Scanner(System.in);
String A = scanner.next();
String B = scanner.next();
char[] A_ = A.toCharArray();
char[] B_ = B.toCharArray();
int length = (A_.length > B_.length ? A_.length : B_.length);
char[] C_ = new char[length + 1];
//这里需要用length的长度重新写A_和B_数组并且把元素都往后靠,也就是字符数组前面的要空出来
int[] A__ = new int[length];
int[] B__ = new int[length];
for (int i = length - 1, j = A_.length - 1, k = B_.length - 1; i >= 0; i--, j--, k--) {
if (j >= 0) {
A__[i] = Integer.parseInt(String.valueOf(A_[j]));
}
if (k >= 0) {
B__[i] = Integer.parseInt(String.valueOf(B_[k]));
}
}
//System.out.println("JK:" + A__[0] + A__[1] + A__[2] + " " + B__[0] + B__[1] + B__[2]);
for (int i = length - 1; i >= 0; i--) {
int a = A__[i];
int b = B__[i];
int sum = a + b;
if (sum < 10){
if (C_[i + 1] == '1'){
if (sum == 9){
C_[i] = '1';
C_[i + 1] = (char)(48);
}else {
C_[i + 1] = (char) (48 + sum + 1);
}
}else {
C_[i + 1] = (char)(48 + sum);
}
}else {
sum = sum - 10;
C_[i] = '1';
if (C_[i + 1] == '1'){
C_[i + 1] = (char)(48 + sum + 1);
}else {
C_[i + 1] = (char)(48 + sum);
}
}
}
//System.out.println(A + " " + B);
//System.out.println(C_[0] + "," + C_[1] + "," + C_[2] + "," + C_[3]);
for (int i = 0; i < C_.length; i++) {
System.out.print(C_[i]);
}
}
}
0.0分
0 人评分
王 2023-02-14 00:50:20 |
谢谢提醒!是调好才发的...也不知道为什么发出来就是这个乱七八糟的样子....也不知道怎么弄...