1.字符串相乘https://leetcode-cn.com/problems/multiply-strings/
学到了for i in range(a, b, c)的用法,其中c为步长
复习了python 字符串的各种操作
对这题的要求和答案不是很理解,要求不能直接将输入转换为整数来处理,但是答案也只是将字符串的每一位字符转换为整数来处理,后面还是有点理解了题目的用意
1 class Solution: 2 def multiply(self, num1: str, num2: str) -> str: 3 if num1 == "0" or num2 == "0": 4 return "0" 5 6 ans = "0" 7 m, n = len(num1), len(num2) 8 for i in range(n - 1, -1, -1): 9 add = 0 10 y = int(num2[i]) 11 curr = ["0"] * (n - i - 1) 12 for j in range(m - 1, -1, -1): 13 product = int(num1[j]) * y + add 14 curr.append(str(product % 10)) 15 add = product // 10 16 if add > 0: 17 curr.append(str(add)) 18 curr = "".join(curr[::-1]) 19 ans = self.addStrings(ans, curr) 20 21 return ans 22 23 def addStrings(self, num1: str, num2: str) -> str: 24 i, j = len(num1) - 1, len(num2) - 1 25 add = 0 26 ans = list() 27 while i >= 0 or j >= 0 or add != 0: 28 x = int(num1[i]) if i >= 0 else 0 29 y = int(num2[j]) if j >= 0 else 0 30 result = x + y + add 31 ans.append(str(result % 10)) 32 add = result // 10 33 i -= 1 34 j -= 1 35 return "".join(ans[::-1])
乘法解就是用一个数组存储每一位的乘积(可能有两位数),然后再进行进位运算
1 class Solution: 2 def multiply(self, num1: str, num2: str) -> str: 3 if num1 == "0" or num2 == "0": 4 return "0" 5 6 m, n = len(num1), len(num2) 7 ansArr = [0] * (m + n) 8 for i in range(m - 1, -1, -1): 9 x = int(num1[i]) 10 for j in range(n - 1, -1, -1): 11 ansArr[i + j + 1] += x * int(num2[j]) 12 13 for i in range(m + n - 1, 0, -1): 14 ansArr[i - 1] += ansArr[i] // 10 15 ansArr[i] %= 10 16 17 index = 1 if ansArr[0] == 0 else 0 18 ans = "".join(str(x) for x in ansArr[index:]) 19 return ans