AcWing 791. 高精度加法-java
原题链接
简单
作者:
ice_73
,
2025-01-17 18:53:07
,
所有人可见
,
阅读 2
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Scanner;
/**
* @author iceewei
* @Description: 大整数算法 acwing-ycx
* @date 2025/1/17
*/
public class BigInteger {
public static void main(String[] args) throws IOException {
String[] s = doInput3();
ArrayList<Integer> A = new ArrayList<>();
ArrayList<Integer> B = new ArrayList<>();
for (int i = s[0].length() - 1; i >= 0 ; i--) A.add(s[0].charAt(i) - '0');
for (int i = s[1].length() - 1; i >= 0 ; i--) B.add(s[1].charAt(i) - '0');
ArrayList<Integer> C = add(A, B);
for (int i = C.size() - 1; i >= 0; i--) System.out.print(C.get(i));
}
// 关键是将问题转化为三个数相加,Ai+Bi+t
private static ArrayList<Integer> add(ArrayList<Integer> A, ArrayList<Integer> B) {
ArrayList<Integer> C = new ArrayList<>();
int t = 0;
for (int i = 0, j = 0; i < A.size() || j < B.size(); i++, j++) {
if (i < A.size()) t += A.get(i);
if (i < B.size()) t += B.get(j);
C.add(t % 10);
t /= 10;
}
if (t > 0) C.add(t);
return C;
}
private static String[] doInput() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer st = new StreamTokenizer(br);
st.ordinaryChars(0, 255);
st.wordChars(33, 255);
String[] s = new String[2];
int counter = 0;
while (st.nextToken()!= StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_WORD) {
s[counter++] = st.sval;
}
}
return s;
}
private static String[] doInput2() throws IOException {
Scanner scanner = new Scanner(System.in);
// 读取多个字符串,以换行符分隔
String[] s = new String[2];
int counter = 0;
while (scanner.hasNextLine()) s[counter++] = scanner.nextLine();
scanner.close();
return s;
}
private static String[] doInput3() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = new String[2];
int counter = 0;
String ss;
while ((ss = br.readLine()) != null) {
s[counter++] = ss;
}
return s;
}
}