Multiply Strings
2018-01-20 19:06
162 查看
Multiply Strings
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
note:
The length of both num1 and num2 is < 110.Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
问题本质是将num1和num2相乘,但是num1和num2是以字符串形式表示的,这个就是问题的难点,这里将其作为手算乘法来思考。
class Solution { public: 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"; } };
相关文章推荐
- leetcode: Multiply Strings
- Multiply Strings
- Leetcode: Multiply Strings
- LeetCode OJ:Multiply Strings
- Multiply Strings
- Multiply Strings(字符串乘法模拟,包含了加法模拟)
- Multiply Strings (Java)
- Leetcode NO.43 Multiply Strings
- leetcode:Multiply Strings
- leetcode----Multiply Strings
- LeetCode - Multiply Strings
- LeetCode: Multiply Strings. Java
- LeetCode Multiply Strings
- Multiply Strings 大数相乘 java
- Multiply Strings
- LeetCode 043 Multiply Strings
- Multiply Strings
- LeetCode 43题之 Multiply Strings
- Multiply Strings
- Leetcode Multiply Strings