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.
Have you met this question in a real interview?
Yes
No
class Solution {
string multiplySingle(string str, char ch, int num){
if(ch=='0') return "0";
int j = str.length()-1;
string ans(num,'0');
int b=ch-'0', carry = 0;
for(;j>=0;j--){
ans=((char)(((str[j]-'0')*b+carry)%10+'0')+ans);
carry=((str[j]-'0')*b+carry)/10;
}
if(carry!=0)
return ((char)(carry+'0'))+ans;
else
return ans;
}
string sum(string str1, string str2){
int i = str1.length()-1;
int j = str2.length()-1;
int carry = 0;
string ans="";
while(i>=0&&j>=0){
ans=((char)(((str1[i]-'0')+(str2[j]-'0')+carry)%10+'0'))+ans;
carry=((str1[i]-'0')+(str2[j]-'0')+carry)/10;
i--,j--;
}
while(i>=0){
ans=((char)(((str1[i]-'0')+carry)%10+'0'))+ans;
carry=((str1[i]-'0')+carry)/10;
i--;
}
while(j>=0){
ans=((char)(((str2[j]-'0')+carry)%10+'0'))+ans;
carry=((str2[j]-'0')+carry)/10;
j--;
}
if(carry!=0)
return ((char)(carry+'0'))+ans;
else
return ans;
}
public:
string multiply(string num1, string num2) {
stack<string> sumStack;
int i,j;
for(i=num2.length()-1,j=0 ; i>=0 ; i--,j++){
sumStack.push(multiplySingle(num1, num2[i],j));
}
while(sumStack.size()!=1){
string s1 = sumStack.top();
sumStack.pop();
string s2 = sumStack.top();
sumStack.pop();
sumStack.push(sum(s1,s2));
}
string tmp = sumStack.top();
if(tmp[0]!='0') return tmp;
for(i=0;i<tmp.length();i++)
if(tmp[i]!='0')
return tmp.substr(i,tmp.length()-i-1);
return "0";
}
};