【LeetCode】43. Multiply Strings 解题报告(Python)

题目分析:

这个题是让两个字符串(数字)相乘返回字符串(数字),其实也就是大数相乘,大数相乘本质就是模拟我们自己计算的过程。

测试代码:

#submit
class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        res = ''
        #因为123*456实际你要先用3乘6所以让字符串倒序
        num1 = num1[::-1]
        num2 = num2[::-1]
        length1 = len(num1)
        length2 = len(num2)
        #临时数组,需要储存计算过程中的中间数值
        temp = [ 0 for i in range(length1 + length2)]
        for i in range(length2):
            for j in range(length1):
                #逐位相乘计算过程中巧妙地对位相加了,比如第一位乘第二位应该加上第二位乘第一位(你可以自己模拟一下)
                temp[i + j] += int(num1[j]) * int(num2[i])
        #把中间结果整合成一个数(串),就是判断是否进位
        for l in range(len(temp)):
            next = int(temp[l] / 10)
            now = temp[l] % 10
            if l + 1 < len(temp):
                temp[l + 1] += next
            res += str(now)
        res = res[::-1]
        #去掉结果前面的0
        while res[0] == '0' and len(res) > 1:
            res = res[1:]
        return res

print(Solution().multiply(num1 = "123", num2 = "456"))  #提交时请删除该行

你可能感兴趣的:(python,LeetCode,LeetCode题目记录)