Skip to content

Commit 7fac82f

Browse files
author
zhongxinming
committed
feat: 43字符串相乘
1 parent e410ff6 commit 7fac82f

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

43_multiply_strings.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
https://leetcode-cn.com/problems/multiply-strings/
3+
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
4+
5+
示例 1:
6+
7+
输入: num1 = "2", num2 = "3"
8+
输出: "6"
9+
示例 2:
10+
11+
输入: num1 = "123", num2 = "456"
12+
输出: "56088"
13+
说明:
14+
15+
num1 和 num2 的长度小于110。
16+
num1 和 num2 只包含数字 0-9。
17+
num1 和 num2 均不以零开头,除非是数字 0 本身。
18+
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
19+
20+
来源:力扣(LeetCode)
21+
链接:https://leetcode-cn.com/problems/multiply-strings
22+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
23+
"""
24+
25+
26+
class Solution:
27+
def multiply(self, num1, num2):
28+
l1, l2 = len(num1), len(num2)
29+
resp = [0] * (l1+l2)
30+
for i in range(l1):
31+
for j in range(l2):
32+
resp[l1+l2-i-j-2] += int(num1[i]) * int(num2[j])
33+
result, add = "", 0
34+
for each in resp:
35+
result, add = str((each+add) % 10) + result, (each+add) // 10
36+
while True:
37+
if result.startswith("0"):
38+
result = result[1:]
39+
continue
40+
break
41+
return result if result else "0"
42+
43+
44+
def main():
45+
print(Solution().multiply('123', '456'))
46+
47+
48+
if __name__ == '__main__':
49+
main()

0 commit comments

Comments
 (0)