【Leetcode】【Medium】Multiply Strings
2015-03-10 02:04
253 查看
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.
解题:
模拟乘法运算,可以完全按照模拟的思路,用num1的每一位乘num2,得到的数组按位保存在结果字符串中,并不断更新。
先把字符串反转,在逻辑上思路会更加清晰,当然不反转也可以。
Note: The numbers can be arbitrarily large and are non-negative.
解题:
模拟乘法运算,可以完全按照模拟的思路,用num1的每一位乘num2,得到的数组按位保存在结果字符串中,并不断更新。
先把字符串反转,在逻辑上思路会更加清晰,当然不反转也可以。
class Solution { public: string multiply(string num1, string num2) { reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); int l1 = num1.size(); int l2 = num2.size(); string res(l1 + l2, '0'); int carry, d; for (int i = 0; i < l1; ++i) { int n1 = num1[i] - '0'; carry = 0; for (int j = 0; j < l2; ++j) { int n2 = num2[j] - '0'; d = n1 * n2 + carry + (res[i+j] - '0'); carry = d / 10; res[i+j] = '0' + (d - carry * 10); } int idx = 0; while (carry != 0) { d = (res[i+l2+idx] - '0') + carry; carry = d / 10; res[i+l2] = '0' + (d - carry * 10); idx++; } } while (!res.empty() && res.back() == '0') res.pop_back(); if (res.empty()) return "0"; reverse(res.begin(), res.end()); return res; } };
相关文章推荐
- [Leetcode 43, medium] Multiply Strings
- LeetCode – Refresh – Multiply Strings
- [LeetCode] 大数问题,相加和相乘,题 Multiply Strings
- [LeetCode] Multiply Strings 解题报告
- LeetCode: Multiply Strings [042]
- 【leetcode】Multiply Strings
- Leetcode 43. Multiply StringsI
- [leetcode]Multiply Strings
- [LeetCode] Multiply Strings
- 52 leetcode - Multiply Strings
- leetcode Multiply Strings
- 【leetcode刷题笔记】Multiply Strings
- LeetCode:Multiply Strings
- Multiply Strings--LeetCode
- leetcode: Multiply Strings
- LeetCode - 43. Multiply Strings
- LeetCode力扣之 Multiply Strings
- LeetCode Problem 43: Multiply Strings
- LeetCode 043 Multiply Strings
- Multiply Strings 两个字符串代表数字相乘@LeetCode