43、字符串相乘
题目:grey_question::
题解:ballot_box_with_check::
和字符串相加相同采用竖式运算思想,分析乘法的竖式运算和加法的竖式运算整体框架不变,都采用双指针,重点在于num1和num2需要选择num1循环一次和num2循环num1次。每当一个num1的元素循环相乘num2的元素后得出一个字符串结果后,左移一位(右边补个0)与上一个结果进行累加。这个累加过程和字符串相加相同。
竖式运算思想,双指针,左移补0累加得结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution: def multiply(self, num1: str, num2: str) -> str: if int(num1) == 0 or int(num2) == 0: return "0" i, carry = len(num1) - 1, 0 res = "" while i >= 0: carry = 0 str1 = "" j = len(num2) - 1 while j >= 0: tmp = int(num1[i]) * int(num2[j]) + carry carry = tmp // 10 str1 = str(tmp % 10) + str1 j = j - 1 str1 = str(carry) + str1 if carry !=0 else str1 for pp in range(len(num1) - 1 - i): str1 = str1 + "0" res = self.addStrings(res, str1) i = i - 1 return res def addStrings(self, num1: str, num2: str): res = "" i, j, carry = len(num1) - 1, len(num2) - 1, 0 while i >= 0 or j >= 0: n1 = int(num1[i]) if i >= 0 else 0 n2 = int(num2[j]) if j >= 0 else 0 tmp = n1 + n2 + carry carry = tmp // 10 res = str(tmp % 10) + res i, j = i - 1, j - 1 return "1" + res if carry == 1 else res
|
上一篇:8、LNMP架构搭建(Nginx)
下一篇:415-字符串相加