题目:
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) {
map<int,string> mp;
mp[0]="0";
string pre="0",now="",mov="";
string mul="",muled="";
if(num1.length()>num2.length()){
mul=num2;
muled=num1;
}
else {
mul=num1;
muled=num2;
}
for(int i=mul.size()-1;i>=0;--i){
if(mp.find(mul[i]-'0')!=mp.end()){
now=mp[mul[i]-'0'];
}
else {
now=multi(muled,mul[i]-'0');
mp[mul[i]-'0']=now;
}
now+=mov;
pre=addtwo(pre,now);
mov+='0';
}
return pre;
}
string addtwo(string s,string t){
int cf=0;
string res="";
for(int i=s.size()-1,j=t.size()-1;i>=0||j>=0;--i,--j){
int tmp=cf;
if(i>=0)tmp+=s[i]-'0';
if(j>=0)tmp+=t[j]-'0';
cf=tmp/10;
tmp=tmp%10;
res.insert(res.begin(),tmp+'0');
}
if(cf)res.insert(res.begin(),cf+'0');
return res;
}
string multi(string muled,int mul){
int cf=0;
string res="";
for(int i=muled.size()-1;i>=0;--i){
int tmp=mul*(muled[i]-'0')+cf;
cf=tmp/10;
tmp=tmp%10;
res.insert(res.begin(),tmp+'0');
}
if(cf)res.insert(res.begin(),cf+'0');
return res;
}
};