Description
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example
Example 1:
Input: num1 = “2”, num2 = “3”
Output: “6”
Example 2:
Input: num1 = “123”, num2 = “456”
Output: “56088”
Submissions
这道题的解题思路是模拟我们计算多位数相乘的过程,而考虑到时间要求,我们可以将两个字符串取反,循环遍历相乘出每一位的结果,存到temp中,再考虑进位,对temp中的每一位进行处理,将余数添加到结果res中,将商进位加到下一个temp元素上,最后将res取反消零,即可得到最终结果.
实现代码如下:
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1==0 or num2==0 or len(num1)>=110 or len(num2)>=110:
return ""
num1 = num1[::-1]
num2 = num2[::-1]
res=""
tmp = [ 0 for i in range(len(num1) + len(num2))]
for i in range(len(num2)):
for j in range(len(num1)):
tmp[i + j] += int(num1[j]) * int(num2[i])
for k in range(len(tmp)):
l = int(tmp[k] / 10)
n = tmp[k] % 10
if k + 1 < len(tmp):
tmp[k + 1] += l
res += str(n)
res = res[::-1]
while res[0] == '0' and len(res) > 1:
res = res[1:]
return res