Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
基本思路:如上图所示,因为两个字符串相乘,长度不定,可以将结果存到一个数组中。我们可以看到num1[i]和num2[j]的乘积最后位置是在indices[i+j]和indices[i+j+1]两个位置上,同时我们知道
一个m位的数乘一个n位的数做多是m+n位。
1 class Solution { 2 public: 3 string multiply(string num1, string num2) {//num1[i] * num2[j]` will be placed 4 //at indices `[i + j`, `i + j + 1]` m*n位数最多m+n位 5 string result; 6 int k = 0, sum = 0; 7 int len1 = num1.size(), len2 = num2.size(); 8 vector<int> res(len1 + len2); 9 for (int i = len1-1; i>=0;i--) 10 { 11 for (int j = len2-1; j >= 0; j--) 12 { 13 int k = (num1[i] - '0')*(num2[j]-'0'); 14 sum = k + res[i + j + 1];//前一次最高位 15 res[i + j + 1] = sum % 10; 16 res[i + j] += sum / 10; 17 } 18 } 19 //去除首位的0 20 int j = len1 + len2 - 1; 21 for (int i = 0; i <len1+len2; i++) 22 { 23 if (res[i] == 0) continue; 24 else 25 { 26 j = i; 27 break; 28 } 29 } 30 for (int i = j; i < len1 + len2; i++) 31 { 32 result += res[i] + '0'; 33 } 34 return result; 35 } 36 };