leetcode-multiply strings
2014-11-11 23:58
316 查看
这道题就是大数运算。
lexi's的想法很好,在操作之前先把num1和num2给逆置,方便操作。
Tenos的文章通过一张图把计算过程直观的展示出来。
Ref:
http://leetcodenotes.wordpress.com/2013/10/20/leetcode-multiply-strings-%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%98%E6%B3%95/ http://www.cnblogs.com/TenosDoIt/p/3735309.html
lexi's的想法很好,在操作之前先把num1和num2给逆置,方便操作。
Tenos的文章通过一张图把计算过程直观的展示出来。
class Solution { public: string multiply(string num1, string num2) { int m = num1.size(); int n = num2.size(); int *d = new int[m+n]; fill_n(d,m+n,0); reverse(num1.begin(),num1.end()); reverse(num2.begin(),num2.end()); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { d[i + j] +=(num1[i]-'0')*(num2[j]-'0'); } } string res(""); for (int i = 0; i < m + n; i++) { int digit = d[i] % 10; int carry = d[i] / 10; res.insert(0,1,char(digit+'0'));//注意在插入char元素时的用法。 if (i < m + n - 1) d[i + 1] += carry; } //此时有可能前面的(下标小的)一些元素是0,要去除。 while (res[0] == '0' && res.length()>1)//是>1,不能是>0,否则结果为0时就删空了。 { res.erase(res.begin()); } return res; } };
Ref:
http://leetcodenotes.wordpress.com/2013/10/20/leetcode-multiply-strings-%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%98%E6%B3%95/ http://www.cnblogs.com/TenosDoIt/p/3735309.html
相关文章推荐
- 【Leetcode】【Medium】Multiply Strings
- Leetcode: Multiply Strings
- [leetcode]Multiply Strings @ Python
- 52 leetcode - Multiply Strings
- Leetcode Multiply Strings
- 【LeetCode练习题】Multiply Strings
- [LeetCode]Multiply Strings
- [leetcode] Multiply Strings
- Leetcode-Multiply Strings
- [Leetcode 43, medium] Multiply Strings
- [LeetCode] Multiply Strings 解题报告
- ★leetcode43_Multiply Strings
- leetcode之Multiply Strings
- leetcode Multiply Strings
- LeetCode Multiply Strings
- LeetCode:Multiply Strings
- Leetcode Multiply Strings
- leetcode---Multiply Strings---大整数乘法
- Leetcode 43 Multiply Strings
- [LeetCode]043-Multiply Strings