刷笔试题的时候遇到了一个大整数乘法的问题,做法就是模拟手工算法,只要注意不能用long来存储,而要使用string。其中还有一些细节需要注意,例如进位,正负号等。
代码如下:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
boolean s = true;
String a = in.next();
String b = in.next();
if (a.charAt(0) == '-') {
a = a.substring(1, a.length());
s = !s;
}
if (b.charAt(0) == '-') {
b = b.substring(1, b.length());
s = !s;
}
String[] resList = new String[1000];
for (int i = 0; i < 1000; i++) {
resList[i] = "0";
}
int plus = 0;
for (int i = b.length() - 1; i >= 0; i--) {
String tRes = "";
int now = Integer.parseInt(b.charAt(i) + "");
for (int j = a.length() - 1; j >= 0; j--) {
int now2 = Integer.parseInt(a.charAt(j) + "");
int tmp = now * now2 + plus;
if (tmp < 10) {
tRes = tRes + tmp;
plus = 0;
} else {
tRes = tRes + (tmp % 10);
plus = tmp / 10;
}
}
if (plus != 0) {
tRes = tRes + plus;
plus = 0;
}
boolean plus2 = false;
for (int y = 0; y < tRes.length(); y++) {
int tmp = Integer.parseInt(tRes.charAt(y) + "") + Integer.parseInt(resList[y + (b.length() - 1 - i)]) + (plus2 ? 1 : 0);
if (tmp < 10) {
resList[y + (b.length() - 1 - i)] = tmp + "";
plus2 = false;
} else {
resList[y + (b.length() - 1 - i)] = tmp - 10 + "";
plus2 = true;
}
}
if (plus2) {
resList[(b.length() - 1 - i) + tRes.length()] = Integer.parseInt(resList[(b.length() - 1 - i) + tRes.length()]) + "1";
plus2 = false;
}
}
boolean start = false;
System.out.print(s ? "" : "-");
for (int i = 999; i >= 0; i--) {
if (!start && resList[i].equals("0")) {
continue;
}
if (!start && !resList[i].equals("0")) {
start = true;
System.out.print(resList[i]);
} else {
System.out.print(resList[i]);
}
}
}
}