Skip to content

Commit 7a29f78

Browse files
authored
Update 043._multiply_strings.md
1 parent 50b25cf commit 7a29f78

File tree

1 file changed

+22
-64
lines changed

1 file changed

+22
-64
lines changed

docs/Leetcode_Solutions/043._multiply_strings.md

Lines changed: 22 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -7,35 +7,14 @@
77

88
## 难度: Medium
99

10-
> 思路1
11-
12-
虽然写了一堆similar problems,拿到的时候也算有思路,但是还是觉得很难写
1310

1411
参考了别人的思路:
1512

1613
1. m位的数字乘以n位的数字的结果最大为m+n位:
1714
* 999*99 < 1000*100 = 100000,最多为3+2 = 5位数。
1815
2. 先将字符串逆序便于从最低位开始计算。
1916

20-
觉得这样写才是最容易理解的,看一个具体的🌰:
21-
22-
```
23-
123 * 456
24-
25-
123
26-
* 456
27-
28-
先把每一位拿来相乘:得到
29-
1 2 3
30-
4 5 6
31-
32-
6 12 18
33-
5 10 15
34-
4 8 12
3517

36-
这样在全部加起来和做进位处理
37-
5 6 0 8 8
38-
```
3918

4019
```python
4120
class Solution(object):
@@ -45,52 +24,31 @@ class Solution(object):
4524
:type num2: str
4625
:rtype: str
4726
"""
48-
if num1 == '0' or num2 == '0' : return '0'
49-
len1,len2 = len(num1),len(num2)
50-
51-
num1 = num1[::-1]
52-
num2 = num2[::-1]
53-
# 99 * 99 < 10000, maxmize 4 digit
54-
arr = [0 for i in range(len1 + len2)]
55-
56-
for i in xrange(len1):
57-
for j in xrange(len2):
58-
arr[i+j] += (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0'))
59-
60-
61-
res = [0 for i in range(len1 + len2)]
62-
63-
for i in range(len(arr)):
64-
res[i] = arr[i] % 10
65-
if i < len(arr) - 1:
66-
arr[i+1] += arr[i]/10
27+
lookup = {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9} # 节省查找时间,避免无休止使用ord函数来得到数字
28+
if num1 == '0' or num2 == '0':
29+
return '0'
30+
num1, num2 = num1[::-1], num2[::-1]
6731

68-
i = len(arr)-1
69-
if res[i] == 0:
70-
i -= 1
71-
return ''.join(str(j) for j in res[:i+1][::-1])
32+
tmp_res = [0 for i in range(len(num1)+len(num2))]
33+
for i in range(len(num1)):
34+
for j in range(len(num2)):
35+
tmp_res[i+j] += lookup[num1[i]] * lookup[num2[j]]
36+
37+
res = [0 for i in range(len(num1)+len(num2))]
38+
for i in range(len(num1)+len(num2)):
39+
res[i] = tmp_res[i] % 10
40+
if i < len(num1)+len(num2)-1:
41+
tmp_res[i+1] += tmp_res[i]/10
42+
return ''.join(str(i) for i in res[::-1]).lstrip('0') 去掉最终结果头部可能存在的‘0
7243
```
7344

74-
> 思路2:
75-
76-
* 1.将字符串转化为数字
77-
* 2.然后相乘
78-
79-
```python
80-
class Solution(object):
45+
觉得这样写才是最容易理解的,看一个具体的🌰:
46+
```
47+
input: num1, num2 = '91', '91'
48+
tmp_res = [1,18,81,0]
49+
res = [1,8,2,8]
8150
82-
def str2num(l):
83-
if len(l)<=1:
84-
return int(l[-1])
85-
return 10**(len(l)-1) * int(l[0]) + Solution.str2num(l[1:])
51+
最终返回 "8281"
8652
87-
def multiply(self, num1, num2):
88-
"""
89-
:type num1: str
90-
:type num2: str
91-
:rtype: str
92-
"""
93-
n1 = Solution.str2num(num1)
94-
n2 = Solution.str2num(num2)
95-
return str(n1*n2)
53+
要注意最终返回头部可能会有‘0’,所以我们用lstrip去除一下
9654
```

0 commit comments

Comments
 (0)