leetcode专题训练 43. Multiply Strings

这道题就是一道大模拟,按照竖式乘法的方法写就好了,需要注意的是,python3与C++不同,python3中有两种除法分别是/与//,/永远都是浮点数除法,而//永远都会对除完结果向下取整。

class Solution:
    def add(self, num1: str, num2: str) -> str:
        if not num1:
            return num2
        if not num2:
            return num1
        i1 = 0
        i2 = 0
        l1 = len(num1)
        l2 = len(num2)
        result = ""
        count = 0
        while i1 < l1 or i2 < l2:
            n1 = 0 if i1 == l1 else int(num1[i1])
            n2 = 0 if i2 == l2 else int(num2[i2])
            su = count+n1+n2
            count = su//10
            result += str(su%10)
            i1 += 0 if i1 == l1 else 1
            i2 += 0 if i2 == l2 else 1
        if count != 0:
            result += '1'
        return result
    
    def multiply(self, num1: str, num2: str) -> str:
        if num1 == "0" or num2 == "0":
            return "0"
        result = ""
        num1 = num1[::-1]
        num2 = num2[::-1]
        zero = 0
        for n1 in num1:
            tmp = ""
            count = 0
            for n2 in num2:
                mult = int(n1)*int(n2)+count
                count = mult//10
                tmp += str(mult%10)
            if count != 0:
                tmp += str(count)
            for i in range(zero):
                tmp = "0"+tmp
            zero += 1
            result = self.add(result, tmp)
        return result[::-1] 
发布了201 篇原创文章 · 获赞 26 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Ema1997/article/details/100395034