Leetcode Multiply Strings 43
来源:互联网 发布:电脑的网络有个感叹号 编辑:程序博客网 时间:2024/05/29 10:12
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.
Subscribe to see which companies asked this question
题目链接
模拟~
class Solution {public: string multiply(string num1, string num2) { int len1=num1.length(); int len2=num2.length(); string ans=""; string temp_ans=""; for(int i=len2-1;i>=0;i--){ int shift=len2-1-i; temp_ans=mul(num1,(int)num2[i]-'0'); //cout<<"temp_ans"<<temp_ans<<endl; temp_ans=reverse(temp_ans); for(int j=0;j<shift;j++){ temp_ans=temp_ans+'0'; } //cout<<"shift:" <<temp_ans<<endl; ans=add(ans,temp_ans); //cout<<"ans="<<ans<<endl; } bool mark=true; for(int i=0;i<ans.length();i++){ if(ans[i]!='0'){ mark=false; break; } } if(mark) ans="0"; return ans; } string reverse(string s){ int len=s.length(); int l=0,r=len-1; while(l<r){ s[l]^=s[r]; s[r]^=s[l]; s[l]^=s[r]; l++; r--; } return s; } string mul(string s,int d){ int len=s.length(); int carry=0,temp=0,r=0; string ans=""; for(int i=len-1;i>=0;i--){ temp=((int)(s[i]-'0'))*d+carry; r=temp%10; carry=temp/10; ans+=to_string(r); } if(carry) ans+=to_string(carry); return ans; } string add(string a,string b){ int la=a.length(); int lb=b.length(); string ans=""; int carry=0,temp=0,r=0,i,j; for(i=la-1,j=lb-1;i>=0 && j>=0;i--,j--){ temp=(int)(a[i]-'0')+(int)(b[j]-'0')+carry; r=temp%10; carry=temp/10; ans+=to_string(r); } for(;i>=0;i--){ temp=(int)(a[i]-'0')+carry; r=temp%10; carry=temp/10; ans+=to_string(r); } for(;j>=0;j--){ temp=(int)(b[j]-'0')+carry; r=temp%10; carry=temp/10; ans+=to_string(r); } if(carry) ans+='1'; ans=reverse(ans); //cout<<"a="<<a<<" b="<<b<<" ans="<<ans<<endl; return ans; }};
0 0
- LeetCode(43) Multiply Strings
- [leetcode 43] Multiply Strings
- [LeetCode 43]Multiply Strings
- leetcode || 43、Multiply Strings
- leetcode-43 Multiply Strings
- Multiply Strings leetcode 43
- leetcode 43: Multiply Strings
- Leetcode 43 Multiply Strings
- leetcode 43 : Multiply Strings
- Leetcode #43 Multiply Strings
- leetcode 43: Multiply Strings
- LeetCode(43) Multiply Strings
- LeetCode-43 Multiply Strings
- Leetcode#43||Multiply Strings
- [Leetcode]#43 Multiply Strings
- leetcode-43 Multiply Strings
- leetcode 43:Multiply Strings
- 【leetcode 43】--------Multiply Strings
- Spring注解详解
- 初始化链表,插入删除节点,遍历链表,链表长度,找出中间节点
- EditorConfig使用和介绍
- English in December
- 类的多重继承
- Leetcode Multiply Strings 43
- Ubuntu下tomcat常用命令
- 随机试验与样本空间
- 字典教程精简版
- Oracle RMAN备份(一)
- 解决mysql数据库中文乱码的问题
- POJ之1003(水题)
- ECMAScript6(ES6)标准之class类的定义、继承及静态方法
- DOS命令查看网络信息