未验证 提交 1746166c 编写于 作者: B BruceCat 提交者: GitHub

【43. 字符串乘法】【Python】

【43. 字符串乘法】【Python】
......@@ -101,7 +101,40 @@ string multiply(string num1, string num2) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
======其他语言代码======
### python
[fengshuu](https://github.com/fengshuu) 提供 Python 解法代码:
```python
def multiply(num1: str, num2: str) -> str:
m, n = len(num1), len(num2)
# 结果最多为 m + n 位数
res = [0] * (m + n)
# 从个位数开始逐位相乘
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
mul = int(num1[i]) * int(num2[j])
# 乘积在 res 对应的索引位置
p1 = i + j
p2 = i + j + 1
# 叠加到 res 上
digit_sum = mul + res[p2]
res[p2] = digit_sum % 10
res[p1] += digit_sum // 10
# 结果前缀可能存的 0(未使用的位)
i = 0
while i < len(res) and res[i] == 0:
i += 1
# 将计算结果转化成字符串
result_str = "".join(str(x) for x in res[i:])
return "0" if len(result_str) == 0 else result_str
```
### java
[Zane Wang](https://github.com/zanecat) 提供 Java 解法代码:
```java
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册