[LeetCode] Multiply Strings 解题报告
来源:互联网 发布:智能电视点歌软件 编辑:程序博客网 时间:2024/06/15 18: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.
» Solve this problem
[解题思路]
大整数乘法,一位一位往上乘,注意进位的处理即可。此外,注意0的处理
[Code]
1: string multiply(string num1, string num2) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: if(num1.size() ==0 || num2.size() ==0) return 0;
5: string res(num1.size()+num2.size()+1, '0');
6: std::reverse(num1.begin(), num1.end());
7: std::reverse(num2.begin(), num2.end());
8: for(int i =0; i < num1.size(); i++)
9: {
10: int dig1 = num1[i] -'0';
11: int carry = 0;
12: for(int j = 0; j< num2.size(); j++)
13: {
14: int dig2 = num2[j] - '0';
15: int exist = res[i+j] -'0';
16: res[i+j] = (dig1*dig2+carry+ exist) % 10 +'0';
17: carry = (dig1*dig2+carry+exist)/10;
18: }
19: if(carry >0)
20: {
21: res[i+num2.size()] = carry + '0';
22: }
23: }
24: std::reverse(res.begin(), res.end());
25: int start =0;
26: while(res[start] =='0' && start < res.size())
27: {
28: start++;
29: }
30: if(start == res.size()) return "0";
31: return res.substr(start, res.size()-start);
32: }
[Note]
1. Line 25~31, 处理乘法过程中在起始处产生的0。 比如, “9133”, “0”,直接乘的结果是“000000”, 而期待结果是“0”
0 0
- 【LeetCode】Multiply Strings 解题报告
- [LeetCode] Multiply Strings 解题报告
- [leetcode] 43. Multiply Strings 解题报告
- [Leetcode] 43. Multiply Strings 解题报告
- Leetcode #43. Multiply Strings 字符串相乘 解题报告
- [leetcode javascript解题]Multiply Strings
- leetcode解题方案--043-- Multiply Strings
- LeetCode-Isomorphic Strings-解题报告
- 【LeetCode】Add Strings 解题报告
- 【LeetCode】Isomorphic Strings 解题报告
- LeetCode: Multiply Strings
- LeetCode Multiply Strings
- LeetCode: Multiply Strings
- [Leetcode] Multiply Strings
- [LeetCode] Multiply Strings
- [Leetcode] Multiply Strings
- LeetCode 45: Multiply Strings
- [LeetCode]Multiply Strings
- 调用活动,通过intent显式调用
- du&df
- [LeetCode] Minimum Depth of Binary Tree
- [LeetCode] Minimum Path Sum 解题报告
- [LeetCode] Minimum Window Substring 解题报告
- [LeetCode] Multiply Strings 解题报告
- [LeetCode] Next Permutation 解题报告
- [LeetCode] Palindrome Number 解题报告
- [LeetCode] Partition List 解题报告
- [LeetCode] Pascal’s Triangle II 解题报告
- Android 之 Fresco 显示圆形图片 之坑
- [LeetCode] Path Sum II 解题报告
- [LeetCode] Permutations 解题报告
- Java环境变量的配置