您的位置:首页 > 其它

LeetCode *** 43. Multiply Strings 

2016-04-24 20:37 399 查看
题目:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: