AcWing 793. 高精度乘法--java
原题链接
简单
作者:
ice_73
,
2025-01-17 22:40:30
,
所有人可见
,
阅读 1
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 Main {
public static void main(String[] args) throws IOException {
String[] s = doInput();
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');
int b = 0;
for (int i = 0; i < s[1].length() ; i++) {
b = b*10 + s[1].charAt(i) - '0';
B.add(s[1].charAt(i) - '0');
}
ArrayList<Integer> C = multiply(A, b);
for (int i = C.size() - 1; i >= 0; i--) {
if (i == C.size() - 1 && C.get(i) == -1) System.out.print("-");
else System.out.print(C.get(i));
}
}
// 关键是将b看作一个整体,多位的b当做一个单位的数一样来做
private static ArrayList<Integer> multiply(ArrayList<Integer> A, int b) {
ArrayList<Integer> C = new ArrayList<>();
int t = 0;
for (int i = 0; i < A.size(); i++) {
t += A.get(i) * b;
C.add(t % 10);
t = t / 10;
}
while (t > 0) {
C.add(t % 10);
t /= 10;
}
while (C.size() > 1 && C.get(C.size() - 1) == 0) C.remove(C.size() - 1);
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;
}
}