package leetcode;
/**
* @Author ******
* @Date 2021/6/8 17:27
* @Param 字符串相乘
*/
public class Leetcode43 {
public static void main(String[] args) {
String num1 = "123", num2 = "456";
String multiply = multiply(num1, num2);
System.out.println(multiply);
}
public static String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
int len1 = num1.length();
int len2 = num2.length();
//两数相乘结果最多为 len1+len2位
int[] res = new int[len1 + len2];
for (int i = len1 - 1; i >= 0; i--) {
int x = num1.charAt(i) - '0';
//第一个数的个位去乘以另一个数的每一位
for (int j = len2 - 1; j >= 0; j--) {
int y = num2.charAt(j) - '0';
//结果放到res数组的第i+j+1位;
res[i + j + 1] += x * y;
}
}
/**
* 1 2 3
* * 1 2 3
* ----------------------
* 3 6 9
* 2 4 6
* 1 2 3
* ------------------------------------------
* 1 4 10 12 9
*/
//进位操作,不能写成 (>= 0)
for (int i = len1 + len2 - 1; i > 0; i--) {
res[i - 1] = res[i - 1] + res[i] / 10;
res[i] = res[i] % 10;
}
//拼接操作,检查最高位有没有数字
StringBuilder builder = new StringBuilder();
int index = res[0] == 0 ? 1 : 0;
while (index < len1 + len2) {
builder.append(res[index]);
index++;
}
return builder.toString();
}
}
03-25
710
07-30
602
08-06
208