题目:
字符串相乘:给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
说明:
num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
思路:
模拟乘法计算的过程来实现。
程序:
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
length1 = len(num1)
length2 = len(num2)
if length1 >= 110:
return " "
if length2 >= 110:
return " "
auxiliary = [0 for _ in range(length1 + length2)]
num1_reversed = list(reversed(num1))
num2_reversed = list(reversed(num2))
index1 = length1 + length2 - 1
for digit1 in num1_reversed:
auxiliary_index = index1
for digit2 in num2_reversed:
auxiliary[auxiliary_index] = auxiliary[auxiliary_index] + int(digit1) * int(digit2)
auxiliary[auxiliary_index - 1] = auxiliary[auxiliary_index - 1] + auxiliary[auxiliary_index] // 10
auxiliary[auxiliary_index] = auxiliary[auxiliary_index] % 10
auxiliary_index = auxiliary_index - 1
index1 = index1 - 1
index2 = 0
while index2 < len(auxiliary):
if auxiliary[index2] == 0:
index2 = index2 + 1
else:
break
result = ""
for index3 in auxiliary[index2:]:
result = result + str(index3)
return result