# [LeetCode] 43. Multiply Strings 字符串相乘

Given two non-negative integers num1 and num2represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"


Note:

1. The length of both num1 and num2 is < 110.
2. Both num1 and num2 contain only digits 0-9.
3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
4. You must not use any built-in BigInteger libraryor convert the inputs to integer directly.

    8 9  <- num2
7 6  <- num1
-------
5 4
4 8
6 3
5 6
-------
6 7 6 4

class Solution {
public:
string multiply(string num1, string num2) {
string res = "";
int m = num1.size(), n = num2.size();
vector<int> vals(m + n);
for (int i = m - 1; i >= 0; --i) {
for (int j = n - 1; j >= 0; --j) {
int mul = (num1[i] - '0') * (num2[j] - '0');
int p1 = i + j, p2 = i + j + 1, sum = mul + vals[p2];
vals[p1] += sum / 10;
vals[p2] = sum % 10;
}
}
for (int val : vals) {
if (!res.empty() || val != 0) res.push_back(val + '0');
}
return res.empty() ? "0" : res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/43

Plus One

https://leetcode.com/problems/multiply-strings/

https://leetcode.com/problems/multiply-strings/discuss/17605/Easiest-JAVA-Solution-with-Graph-Explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2015-04-06 06:53  Grandyang  阅读(24476)  评论(10编辑  收藏  举报