LeetCode43——Multiply Strings(两个字符串表示的整数相乘)???
来源:互联网 发布:红米4a支持网络频段 编辑:程序博客网 时间:2024/05/19 06:47
题目:
参考解法:
法一:
This is the standard manual multiplication algorithm. We use two nested for loops, working backward from the end of each input number. We pre-allocate our result and accumulate our partial result in there. One special case to note is when our carry requires us to write to our sum string outside of our for loop.
At the end, we trim any leading zeros, or return 0 if we computed nothing but zeros.
string multiply(string num1, string num2) { string sum(num1.size() + num2.size(), '0'); for (int i = num1.size() - 1; 0 <= i; --i) { int carry = 0; for (int j = num2.size() - 1; 0 <= j; --j) { int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry; sum[i + j + 1] = tmp % 10 + '0'; carry = tmp / 10; } sum[i] += carry; } size_t startpos = sum.find_first_not_of("0"); if (string::npos != startpos) { return sum.substr(startpos); } return "0";}
法二:The key part is to use a vector to store all digits REVERSELY. after the calculation, find the rightmost NON-Zero digits and convert it to a string.
class Solution {public: string multiply(string num1, string num2) { unsigned int l1=num1.size(),l2=num2.size(); if (l1==0||l2==0) return "0"; vector<int> v(l1+l2,0); for (unsigned int i=0;i<l1;i++){ int carry=0; int n1=(int)(num1[l1-i-1]-'0');//Calculate from rightmost to left for (unsigned int j=0;j<l2;j++){ int n2=(num2[l2-j-1]-'0');//Calculate from rightmost to left int sum=n1*n2+v[i+j]+carry; carry=sum/10; v[i+j]=sum%10; } if (carry>0) v[i+l2]+=carry; } int start=l1+l2-1; while(v[start]==0) start--; if (start==-1) return "0"; string s=""; for (int i=start;i>=0;i--) s+=(char)(v[i]+'0'); return s; }};
分析:
两个数相乘,最后的结果的长度,最大为两个乘数的长度之和。
阅读全文
0 0
- LeetCode43——Multiply Strings(两个字符串表示的整数相乘)???
- LeetCode43——Multiply Strings
- [LeetCode43] Multiply Strings
- Leetcode43 Multiply Strings
- LeetCode43. Multiply Strings
- leetcode43 Multiply Strings
- LeetCode43 Multiply Strings
- LeetCode43 Multiply Strings
- leetcode43. Multiply Strings
- LeetCode | Multiply Strings(字符串相乘)
- Multiply Strings 两个字符串代表数字相乘@LeetCode
- [LeetCode] Multiply Strings 字符串相乘
- Multiply Strings 两个字符串的乘法
- LeetCode Multiply Strings(大整数相乘)
- leetcode-43. Multiply Strings(大整数相乘)
- Multiply Strings(大数相乘)
- leetcode 43 Multiply Strings (字符串相乘)
- 长整数相乘的字符串表示法
- activemq 发布订阅模式
- ELK搭建
- MySQL学习笔记2-System administration(set password)II
- Web学习笔记_03
- Ubuntu下安装多个版本的opencv,以及切换使用
- LeetCode43——Multiply Strings(两个字符串表示的整数相乘)???
- android :StartupAbortedException
- 大型网站架构之分布式消息列队
- 2017年网页ui设计有哪些新趋势?
- CocoaPods安装、卸载、使用说明(Mac ox 10.11+)
- Shell
- c++builder读取标准ini文件操作
- 沿途感想--研想(2)
- 求助!ssdclient.jar 莫名出现的jar包进程