7
7
8
8
## 难度: Medium
9
9
10
- > 思路1
11
-
12
- 虽然写了一堆similar problems,拿到的时候也算有思路,但是还是觉得很难写
13
10
14
11
参考了别人的思路:
15
12
16
13
1 . m位的数字乘以n位的数字的结果最大为m+n位:
17
14
* 999* 99 < 1000* 100 = 100000,最多为3+2 = 5位数。
18
15
2 . 先将字符串逆序便于从最低位开始计算。
19
16
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
35
17
36
- 这样在全部加起来和做进位处理
37
- 5 6 0 8 8
38
- ```
39
18
40
19
``` python
41
20
class Solution (object ):
@@ -45,52 +24,31 @@ class Solution(object):
45
24
:type num2: str
46
25
:rtype: str
47
26
"""
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 ]
67
31
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 ’
72
43
```
73
44
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]
81
50
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"
86
52
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去除一下
96
54
```
0 commit comments