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.
分析:
代码:
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; } };
相关文章推荐
- 区间信息的维护与查询_1 2016.4.24
- HDU5672String(尺标法)
- 第8周学习进度
- Android:Java代码添加按钮
- PHP编程----for循环的妙用
- C++中static_cast/const_cast/dynamic_cast/reinterpret_cast的区别和使用
- 3. Longest Substring Without Repeating Characters
- hadoop HA启动时 两个namenode节点都是standby,解决办法
- C++ 学习基础篇(一)—— C++与C 的区别
- C++中static_cast/const_cast/dynamic_cast/reinterpret_cast的区别和使用
- php课堂笔记
- 学习进度07
- HashMap、HashTable与ConcurrentHashMap区别
- php模拟post上传图片
- Red and Black
- 文章标题 c语言中关于串的相关知识以及操作
- 两个队列模拟栈
- HDU2602_01背包问题
- WebView加载网页-进度显示-网络上传图片并压缩
- Android基础学习第二篇—Activity