> For the complete documentation index, see [llms.txt](https://kerasnoone.gitbook.io/garnet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kerasnoone.gitbook.io/garnet/suan-fa/zi-fu-chuan/43-zi-fu-chuan-xiang-cheng.md).

# \[43]\[中等] 字符串相乘

## 题目描述

给定两个以字符串形式表示的非负整数 num1 和 num2，返回 num1 和 num2 的乘积，它们的乘积也表示为字符串形式。

示例 1:

```
输入: num1 = "2", num2 = "3"
输出: "6"
```

示例 2:

```
输入: num1 = "123", num2 = "456"
输出: "56088"
```

说明：

* num1 和 num2 的长度小于110。
* num1 和 num2 只包含数字 0-9。
* num1 和 num2 均不以零开头，除非是数字 0 本身。
* 不能使用任何标准库的大数类型（比如 BigInteger）或直接将输入转换为整数来处理。

## 解题思路

竖式乘法, 内外双层循环跑不了, 简单的思路就是**先不考虑进位**, 将`num1`的第$$i$$个字符和`num2`的第$$j$$个字符计算, 都放在结果的第$$i+j$$位上(竖式乘法的思路).

然后将所有的结果计算出来, 每位的结果都各自累加, 再最后对结果列表循环过一遍, 处理进位.

```python
class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        n, m = len(num1), len(num2)
        if (n == 1 and num1 == '0') or (m == 1 and num2 == '0'):
            return '0'
        tmp_result = [0] * (n + m)

        num1, num2 = num1[::-1], num2[::-1]
        for i in range(n):
            t1 = int(num1[i])
            for j in range(m):
                t2 = int(num2[j])
                tmp_result[i + j] += t1 * t2

        carry = 0
        for i, t in enumerate(tmp_result):
            t += carry
            carry, real = t // 10, t % 10
            tmp_result[i] = str(real)

        if carry > 0:
            tmp_result.append(str(carry))

        tmp_result = tmp_result[:-1] if tmp_result[-1] == '0' else tmp_result

        return ''.join(tmp_result[::-1])
```
