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.
- Converting the input string to integer is NOT allowed.
- You should NOT use internal library such as BigInteger.
分析: 模拟乘法,注意下细节和进位
class Solution {
public:
string multiply(string num1, string num2) {
int size1 = num1.size(), size2 = num2.size();
if(size1==0 || size2==0) return 0;
vector<int> res(size1+size2,0);
for(int i =0; i< size1; i++ ){
int carry = 0;
int n1 = (int)(num1[size1-1-i]-'0');
for(int j =0; j< size2; j++){
int n2 = (int)(num2[size2-1-j]-'0');
int sum = (n1*n2+carry+res[i+j]);
carry = sum/10;
res[i+j] = sum%10;
}
res[i+size2] += carry==0? 0: carry;
}
// for(auto t: res)
// cout << t<<" ";
int start =size1+size2-1;
while(start>=0 && res[start]==0) start--;
if(start==-1) return "0";
string s="";
for(;start>=0; start--)
s+= (char)(res[start]+'0');
return s; }
};