From 6860be44b844b4147d68bb5501af87a59d390061 Mon Sep 17 00:00:00 2001 From: "shuhaofeng2@creditease.cn" Date: Wed, 11 Nov 2020 23:21:14 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=B8=BA=2043-=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E4=B9=98=E6=B3=95=20=E6=B7=BB=E5=8A=A0python=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feat: 为 43-字符串乘法 添加python解法1 feat: 为 43-字符串乘法 添加python解法3 --- ...46\344\270\262\344\271\230\346\263\225.md" | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\255\227\347\254\246\344\270\262\344\271\230\346\263\225.md" "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\255\227\347\254\246\344\270\262\344\271\230\346\263\225.md" index 0273744..8349f7a 100644 --- "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\255\227\347\254\246\344\270\262\344\271\230\346\263\225.md" +++ "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\255\227\347\254\246\344\270\262\344\271\230\346\263\225.md" @@ -101,4 +101,33 @@ string multiply(string num1, string num2) {

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +[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 +``` \ No newline at end of file -- GitLab