LeetCode 43. 字符串相乘

题目描述

🔥 43. 字符串相乘

image-20220916001134670

思路分析

竖式乘法

image-20220805141950396

image-20220912202047599

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func multiply(num1 string, num2 string) string {
	if num1 == "0" || num2 == "0" {
		return "0"
	}
	m, n := len(num1), len(num2)
	res := make([]int, m+n)
	for i := m - 1; i >= 0; i-- {
		for j := n - 1; j >= 0; j-- {
			mul := int(num1[i]-'0') * int(num2[j]-'0')
			sum := mul + res[i+j+1]
			res[i+j+1] = sum % 10
			res[i+j] += sum / 10
		}
	}
	var sb strings.Builder
	for _, digit := range res {
		sb.WriteString(fmt.Sprintf("%d", digit))
	}
	return strings.TrimLeft(sb.String(), "0")
}

🍏 点击查看 Java 题解(一)

1
write your code here

🍏 点击查看 Java 题解(二)

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2022/15837549
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!