Given two non-negative integers
num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = “2”, num2 = “3”
Output: “6”
Example 2:
Input: num1 = “123”, num2 = “456”
Output: “56088”
Constraints:
1 <= num1.length, num2.length <= 200
num1
and num2
consist of digits only.* Both
num1
and num2
do not contain any leading zero, except the number 0
itself.题目大意:
求字符串乘法结果
解题思路:
模拟小学乘法
解题步骤:
N/A
注意事项:
- 模拟小学乘法,开一个大小为len(num1) + len(num2)的整数数组,内外循环计算每位结果。这位可能是大于20的数,如20, 30..。计算前先反转输入,得到最后结果后也反转。
- 结果要消除前缀0,但注意0乘以0的情况会返回空,所以要特别处理。
Python代码:
1 | def multiply(self, num1: str, num2: str) -> str: |
算法分析:
时间复杂度为O(n)
,空间复杂度O(1)