题目
给定两个以字符串形式表示的非负整数 num1
和 num2
,返回 num1
和 num2
的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = "2", num2 = "3" 输出: "6"
示例 2:
输入: num1 = "123", num2 = "456" 输出: "56088"
解题
方法一:用int方法转为正数
但是题目要求了,不能使用这种方法,所以不推荐
class Solution: def multiply(self, num1: str, num2: str) -> str: return str(int(num1)*int(num2))
方法二:做加法
class Solution: def multiply(self, num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" ans = "0" m, n = len(num1), len(num2) for i in range(n - 1, -1, -1): add = 0 y = int(num2[i]) curr = "0" * (n-1-i) for j in range(m - 1, -1, -1): add += int(num1[j]) * y curr+= str(add% 10) add = add// 10 if add > 0: curr+=str(add) curr = curr[::-1] ans = self.addStrings(ans, curr) return ans def addStrings(self, num1: str, num2: str) -> str: i, j = len(num1) - 1, len(num2) - 1 add = 0 ans = "" while i >= 0 or j >= 0 or add != 0: x = int(num1[i]) if i >= 0 else 0 y = int(num2[j]) if j >= 0 else 0 add += x + y ans+= str(add % 10) add = add // 10 i -= 1 j -= 1 return ans[::-1]
mutiply另外一种看起来简洁的写法
class Solution: def multiply(self, num1: str, num2: str) -> str: if num1=='0' or num2=='0': return '0' ans = '0' for i,m in enumerate(num1[::-1]): curr = '0'*i add = 0 for n in num2[::-1]: add += int(m)*int(n) curr += str(add%10) add//=10 if add: curr+=str(add) curr = curr[::-1] res = self.addString(res,curr) return ans def addString(self,num1:str,num2:str): i = len(num1)-1 j = len(num2)-1 add = 0 ans = '' while i>=0 or j>=0 or add!=0: x = int(num1[i]) if i>=0 else 0 y = int(num2[j]) if j>=0 else 0 add += x+y ans += str(add%10) add //= 10 i -= 1 j -= 1 return ans[::-1]