LeetCode 题解工作台
字符串相乘
给定两个以字符串形式表示的非负整数 num1 和 num2 ,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。 注意: 不能使用任何内置的 BigInteger 库或直接将输入转换为整数。 示例 1: 输入: num1 = "2", num2 = "3" 输出: "6" 示例 2…
3
题型
10
代码语言
3
相关题
当前训练重点
中等 · 数学·string
答案摘要
假设 和 的长度分别为 和 ,则它们的乘积的长度最多为 $m + n$。 证明如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数。
示例 1:
输入: num1 = "2", num2 = "3" 输出: "6"
示例 2:
输入: num1 = "123", num2 = "456" 输出: "56088"
提示:
1 <= num1.length, num2.length <= 200num1和num2只能由数字组成。num1和num2都不包含任何前导零,除了数字0本身。
解题思路
方法一:数学乘法模拟
假设 和 的长度分别为 和 ,则它们的乘积的长度最多为 。
证明如下:
- 如果 和 都取最小值,那么它们的乘积为 ,长度为 。
- 如果 和 都取最大值,那么它们的乘积为 ,长度为 。
因此,我们可以申请一个长度为 的数组,用于存储乘积的每一位。
从低位到高位,依次计算乘积的每一位,最后将数组转换为字符串即可。
注意判断最高位是否为 ,如果是,则去掉。
时间复杂度 ,空间复杂度 。其中 和 分别为 和 的长度。
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
m, n = len(num1), len(num2)
arr = [0] * (m + n)
for i in range(m - 1, -1, -1):
a = int(num1[i])
for j in range(n - 1, -1, -1):
b = int(num2[j])
arr[i + j + 1] += a * b
for i in range(m + n - 1, 0, -1):
arr[i - 1] += arr[i] // 10
arr[i] %= 10
i = 0 if arr[0] else 1
return "".join(str(x) for x in arr[i:])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(M * N) because each digit in num1 multiplies with each digit in num2. Space complexity is O(M + N) to store intermediate results in the result array representing the product of M and N digit numbers. |
| 空间 | O(M + N) |
面试官常问的追问
外企场景- question_mark
Check if the candidate handles carry propagation correctly in a digit-by-digit simulation.
- question_mark
Watch for attempts to convert strings directly to integers, which violates constraints.
- question_mark
Assess whether the candidate efficiently manages the result array without unnecessary string concatenations.
常见陷阱
外企场景- error
Failing to reverse the input strings before multiplying can misalign digits and produce incorrect results.
- error
Ignoring carry propagation leads to digits exceeding 9 and incorrect final products.
- error
Returning partial results or failing to remove leading zeros may cause format errors in the output string.
进阶变体
外企场景- arrow_right_alt
Multiply Strings using recursive divide-and-conquer instead of iterative simulation for large digit inputs.
- arrow_right_alt
Implement multiplication with memory optimization to reduce the intermediate array size to a minimal representation.
- arrow_right_alt
Handle negative numbers represented as strings, extending the simulation to include sign management.