[LeetCode]Multiply Strings
2015-04-24 22:01
411 查看
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.
给定两个字符串表示的数,要求求这两个数的乘积,乘积用字符串表示。其中,字符串表示的数是非负数。
写的很粗糙,一点都不优雅QAQ
Note: The numbers can be arbitrarily large and are non-negative.
给定两个字符串表示的数,要求求这两个数的乘积,乘积用字符串表示。其中,字符串表示的数是非负数。
写的很粗糙,一点都不优雅QAQ
string multiply(string num1, string num2) { vector<string> ans_temp; string temp; //先计算出num1表示的数与num2表示的数的各个位的乘积,乘积用字符串表示,保存在ans_temp中 for (int i = num2.length() - 1, count = 0; i >= 0; i--,count++){ int up = 0; string temp; for (int j = num1.length() - 1; j >= 0; j--){ int last = ((num2[i] - '0')*(num1[j] - '0') +up)% 10; up = ((num2[i] - '0')*(num1[j] - '0') + up) / 10; temp.push_back(last + '0'); } if (up) temp.push_back(up + '0');//最高位有进位 reverse(temp.begin(),temp.end()); for (int k = count; k > 0; k--){ temp.push_back('0');//低位补零 } reverse(temp.begin(), temp.end()); ans_temp.push_back(temp); temp = ""; } int up = 0; string ans; int t = 0; //求和 for (int j = 0; j < ans_temp.size(); j++){ for (int i = t; i <ans_temp[j].length(); i++){ int a = up; for (int k = j; k < ans_temp.size(); k++){ a += (ans_temp[k][i] - '0'); } up = a / 10; a = a % 10; ans.push_back(a + '0'); } t = ans_temp[j].length(); } if (up){ ans.push_back(up+'0'); } reverse(ans.begin(), ans.end()); if (ans[0] == '0') return "0"; return ans; }
相关文章推荐
- leetcode 日经贴,Cpp code -Multiply Strings
- LeetCode - Multiply Strings
- [LeetCode] Multiply Strings
- LeetCode(43)Multiply Strings
- [LeetCode] Multiply Strings
- leetcode:Multiply Strings +…
- LeetCode 43 Multiply Strings(高精度乘法)
- Leetcode: Multiply Strings
- [leetcode]Multiply Strings
- [Leetcode 43 Multiply Strings]大数乘法,回到乘法本身的“最基础”去优化
- LeetCode_43---Multiply Strings
- [LeetCode] Multiply Strings 解题报告
- [leetcode] Multiply Strings
- leetcode-43 Multiply Strings
- Leetcode: Multiply Strings
- LeetCode-Multiply Strings
- [leetcode] 43.Multiply Strings
- LeetCode Multiply Strings
- Leetcode Multiply Strings
- LeetCode: Multiply Strings