题解 | 大数乘法
大数乘法
https://www.nowcoder.com/practice/c4c488d4d40d4c4e9824c3650f7d5571
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串 第一个整数
* @param t string字符串 第二个整数
* @return string字符串
*/
public String solve (String s, String t) {
// write code here
//竖式乘法:先各位相乘,再大数相加
String a = new StringBuffer(s).reverse().toString();
String b = new StringBuffer(t).reverse().toString();
String c = "";
String zero = ""; //加0,补位数
for (int i = 0; i < b.length(); i++) {
int x = b.charAt(i) - '0';
String temp = zero; //每次相乘得到的数
int flag = 0; //进位符
for (int j = 0; j < a.length(); j++) { //各位相乘
int result = x * (a.charAt(j) - '0') + flag;
int add = result % 10;
flag = result / 10;
temp = temp + add;
}
temp = (flag != 0) ? temp + flag : temp; //就是这次b[i]倒过来
flag = 0; //进位符清零,用作相加的进位
String end = "";
//temp和c相加,大数相加
for (int j = 0, k = 0; j < c.length() || k < temp.length(); j++, k++) {
int y = (j < c.length()) ? (c.charAt(j) - '0') : 0;
int z = (k < temp.length()) ? (temp.charAt(k) - '0') : 0;
int result = y + z + flag;
int add = result % 10;
flag = result / 10;
end = end + add;
}
c = (flag != 0) ? (end + flag) : end; //此次大数相加的结果
zero = zero + 0;
}
if (c.matches("^0+$")) c = "0";
return new StringBuffer(c).reverse().toString();
}
}
