题目传送地址: ​​https://leetcode.cn/problems/multiply-strings/​

Leetcode 43. 字符串相乘_java


解题思路:

比如1515的计算过程。 我们先算155=0075 15*10=0150;

代码如下:

public static String multiply(String num1, String num2) {
//处理特殊边界情况
if("0".equals(num1)||"0".equals(num2)){
return "0";
}
String[] strings = new String[num2.length()];
for (int i = num2.length() - 1; i >= 0; i--) {
char c = num2.charAt(i);
int i2 = c - '0';
int sum = 0;
int carry = 0;
StringBuilder stringBuilder = new StringBuilder();
int j = 0;
while (j < num2.length() - 1 - i) {
stringBuilder.append(0);
j++;
}
for (int n = num1.length() - 1; n >= 0; n--) {
int i3 = num1.charAt(n) - '0';
sum = i2 * i3+carry;
carry = sum / 10;
sum = sum % 10;
stringBuilder.insert(0,sum);
}
if(carry!=0){
stringBuilder.insert(0,carry);
}
while (stringBuilder.length() < num1.length() + num2.length()) {
stringBuilder.insert(0, 0);
}
strings[num2.length() - 1 - i] = stringBuilder.toString();
}
int carry = 0;//进位
StringBuilder result = new StringBuilder();
for (int j = num1.length() + num2.length() - 1; j >= 0; j--) {
int sum = 0;
for (String str : strings) {
int i = str.charAt(j) - '0';
sum += i;
}
sum += carry;
carry = sum / 10;
sum = sum % 10;
result.insert(0, sum);
}
//去掉前置0
return result.toString().replaceAll("^(0+)", "");
}