43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

两个字符串的位数做乘法,每次计算进位。
当前位等于自身加上计算结果的个位(由于有之前的进位存在。),下一位等于计算结果的十位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public String multiply(String num1, String num2) {
int m = num1.length();
int n = num2.length();
if( num1.equals("0") || num2.equals("0")){
return "0";
}
int[] product = new int[m+n];

char[] arr1 = num1.toCharArray();
char[] arr2 = num2.toCharArray();

for(int i = m-1; i >= 0; i--){
for(int j = n-1; j >=0; j--){
int sum = product[i+j+1] + (arr1[i] - '0') * (arr2[j] - '0');
int curr = sum % 10;
int carry = sum / 10;

product[i+j] += carry;
product[i+j+1] = curr;
}
}
StringBuffer sb = new StringBuffer();
for(int k = 0; k < m+n; k++ ){
if(k == 0 && product[k] == 0 ) continue;
sb.append(product[k]);
}
return sb.toString();
}
}
Author

Xander

Posted on

2022-04-23

Updated on

2022-04-23

Licensed under

Comments