Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
class Solution {
public:
string multiply(string num1, string num2) {
if(num1 == "0" || num2=="0") return "0";
int len1 = num1.size();
int len2 = num2.size();
int flag = 0;
int k = 0;
string str(len1 + len2, '0');
for(int i=len1-1;i>=0;i--){
int a = num1[i] - '0';
for(int j=len2-1, k=i+len2; j>=0; j--,k--){
int b = num2[j] - '0';
int unit = a*b %10;
int cur_unit = str[k] - '0';
str[k] = (cur_unit + unit + flag)%10 + '0';
//flag为每次进位的值,待下次计算时加入
flag = (a*b - unit)/10 + (cur_unit + unit + flag)/10;
}
//处理每次循环到num2的最高位后的flag
int m = i;
while(flag){
int cur = str[m] - '0';
str[m] = (cur + flag)%10 + '0';
flag = (cur + flag)/10;
m--;
}
}
int x = 0;
//去除str前面的‘0’
while (str[x] == '0')
x++;
str = str.substr(x,len1+len2-x);
return str;
}
};