0%

LeetCode: 43. Multiply Strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
string multiply(string num1, string num2) {
int len = num1.size() + num2.size();
vector<int> nums(len, 0);
for(int i=num1.size()-1;i>=0;--i)
for(int j=num2.size()-1;j>=0;--j)
nums[i+j+1]+=(num1[i]-'0')*(num2[j]-'0');
for(int i=len-1;i>0;--i)
{
nums[i-1]+=nums[i]/10;
nums[i]=nums[i]%10;
}

string ret;
int idx=0;
while(nums[idx]==0 && idx!=len-1)
++idx;
while(idx<len)
ret+=(nums[idx++]+'0');
return ret;
}
};