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.
class Solution {
public:
string multiply(string num1, string num2) {
if(num1.size()>110 || num2.size()>110) return 0;
if(num1.empty() || num2.empty() ) return 0;
string result;
for(int i=num2.size()-1;i>=0;i--){
int carry=0;
int numi= num2[i]-'0';
string solution;
for(int j=num1.size()-1;j>=0;j--){
int numj=num1[j]-'0';
int multi=(numi*numj+carry)%10;
carry=(numi*numj+carry)/10;
solution.insert(solution.begin(),multi+'0');
}
if(carry!=0) solution.insert(solution.begin(),carry+'0');
for(int j=num2.size()-1;j>i;j--) solution.push_back('0');
result=add(result,solution);
}
size_t start=0;
while(result[start] == '0' && start < result.size()-1){
start++;
}
return result.substr(start, result.size());
}
string add(string a,string b){
int carry=0;
string result;
for(int i=a.size()-1,j=b.size()-1; i>=0||j>=0; i--,j--){
int ai= i>=0?a[i]-'0':0;
int bj= j>=0?b[j]-'0':0;
int val=(ai+bj+carry)%10;
carry=(ai+bj+carry)/10;
result.insert(result.begin(),val+'0');
}
if(carry==1)
result.insert(result.begin(),'1');
return result;
}
};