File tree 1 file changed +63
-0
lines changed
1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ #### 43. 字符串相乘
2
+
3
+ 难度:中等
4
+
5
+ ---
6
+
7
+ 给定两个以字符串形式表示的非负整数 ` num1 ` 和 ` num2 ` ,返回 ` num1 ` 和 ` num2 ` 的乘积,它们的乘积也表示为字符串形式。
8
+
9
+ ** 注意:** 不能使用任何内置的 BigInteger 库或直接将输入转换为整数。
10
+
11
+ ** 示例 1:**
12
+
13
+ ```
14
+ 输入: num1 = "2", num2 = "3"
15
+ 输出: "6"
16
+ ```
17
+
18
+ ** 示例 2:**
19
+
20
+ ```
21
+ 输入: num1 = "123", num2 = "456"
22
+ 输出: "56088"
23
+ ```
24
+
25
+ ** 提示:**
26
+
27
+ * ` 1 <= num1.length, num2.length <= 200 `
28
+ * ` num1 ` 和 ` num2 ` 只能由数字组成。
29
+ * ` num1 ` 和 ` num2 ` 都不包含任何前导零,除了数字0本身。
30
+
31
+ ---
32
+
33
+ 模拟:
34
+
35
+ ``` Java
36
+ func multiply(num1 string, num2 string) string {
37
+ if num1 == " 0" || num2 == " 0" {
38
+ return " 0"
39
+ }
40
+ m, n : = len(num1), len(num2)
41
+ array : = make([]int , m+ n) // 两数相乘,最大长度为 m+n
42
+ for i : = m - 1 ; i >= 0 ; i-- {
43
+ temp1 : = int(num1[i] - ' 0' )
44
+ for j : = n - 1 ; j >= 0 ; j-- {
45
+ temp2 : = int(num2[j] - ' 0' )
46
+ array[i+ j+ 1 ] += temp1 * temp2 // 存储的是乘积,没向前进位
47
+ }
48
+ }
49
+ // 处理进位,i的进位位置在i-1位置
50
+ for i : = len(array) - 1 ; i > 0 ; i-- {
51
+ array[i- 1 ] += array[i] / 10
52
+ array[i] %= 10
53
+ }
54
+ res : = " "
55
+ for i : = range array {
56
+ if i == 0 && array[i] == 0 { // 如果第0位为0,则需要处理
57
+ continue
58
+ }
59
+ res += string(array[i] + ' 0' )
60
+ }
61
+ return res
62
+ }
63
+ ```
You can’t perform that action at this time.
0 commit comments