-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiply Strings
More file actions
31 lines (31 loc) · 863 Bytes
/
Copy pathMultiply Strings
File metadata and controls
31 lines (31 loc) · 863 Bytes
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
31
class Solution {
public:
string multiply(string num1, string num2) {
if(num1.empty() or num2.empty()) return "0";
int len1 = num1.size(), len2 = num2.size();
string ans(len1+len2, '0');
for(int i = len1 - 1; i >= 0; i--)
{
for(int j = len2 - 1; j >= 0; j--)
{
int x = num1[i]-'0';
int y = num2[j]-'0';
int mult = x*y;
int ind1 = i+j;
int ind2 = i+j+1;
mult += ans[ind2] - '0';
ans[ind1] += mult/10;
ans[ind2] = mult%10 + '0';
}
}
int i;
for( i = 0; i < len1+len2; i++)
{
if(ans[i] != '0') break;
}
if(i==len1+len2) i--;
if(i!=0)
ans.erase(0, i);
return ans;
}
};