Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3" Output: "6"
Example 2:
Input: num1 = "123", num2 = "456" Output: "56088"
计算大数相乘。
比较简单的思路就是直接根据每个数字所在位置进行计算。如下所示
class Solution:
def multiply(self, num1: str, num2: str) -> str:
res=0
for i,n1 in enumerate(num1[::-1]):
for j,n2 in enumerate(num2[::-1]):
res+=int(n1)*(10**i)*int(n2)*(10**j)
return str(res)
或者用dp算法,能快一些。计算dp[i+j]初的结果,然后dp[i+j+1]要进位,然后dp[i+j]再取余数(回归一位数)。
然后去除数字首位的0,返回字符串。
class Solution:
def multiply(self, num1: str, num2: str) -> str:
dp=[0]*(len(num1)+len(num2))
for i,n1 in enumerate(num1[::-1]):
for j,n2 in enumerate(num2[::-1]):
dp[i+j]+=int(n1)*int(n2)
dp[i+j+1]+=dp[i+j]//10
dp[i+j]%=10
while dp[-1]==0 and len(dp)>1:dp.pop()
return ''.join(str(a) for a in dp[::-1])