Leetcode 43. Multiply Strings

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 43. Multiply Strings相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

2. Solution

**解析:**Version 1,直接按照学习的乘法计算方式来求解,先计算第二个数的每一位(从个位开始)乘以第一个数,再将得出的结果加到一起。Version 2采用另一种方式实现。

  • Version 1
class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if num1 == '0' or num2 == '0':
            return '0'
        result = []
        carry = 0
        num1 = list(map(int, num1))
        num2 = list(map(int, num2))
        for i in range(len(num2) -1, -1, -1):
            if num2[i] == 0:
                continue
            temp = self.mul(num1, num2[i], len(num2) - i - 1)
            result = self.add(result, temp)
        p = [str(num) for num in result]
        return ''.join(p)[::-1]


    def mul(self, num1, b, index):
        result = []
        carry = 0
        for a in reversed(num1):
            product = a * b + carry
            result.append(product % 10)
            carry = product // 10
        if carry > 0:
            result.append(carry)
        return [0] * index + result


    def add(self, a, b):
        carry = 0
        for i in range(len(b)):
            if i < len(a):
                x = a[i]
            else:
                x = 0
            y = b[i]
            sum = x + y + carry
            b[i] = sum % 10
            carry = sum // 10
        if carry > 0:
            b.append(carry)
        return b
  • Version 2
class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if num1 == '0' or num2 == '0':
            return '0'
        num1 = list(map(int, num1))
        num2 = list(map(int, num2))
        m = len(num1)
        n = len(num2)
        result = [0] * (m + n)
        for i in range(m-1, -1, -1):
            for j in range(n-1, -1, -1):
                product = num1[i] * num2[j]
                sum = product + result[i+j+1]
                result[i+j+1] = sum % 10
                result[i+j] += sum // 10
        result = list(map(str, result))
        result = ''.join(result).lstrip('0')
        return result

Reference

  1. https://leetcode.com/problems/multiply-strings//

以上是关于Leetcode 43. Multiply Strings的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 43. Multiply Strings

Leetcode43. Multiply Strings

LeetCode 43. Multiply Strings

<LeetCode OJ> 43. Multiply Strings

LeetCode题意分析&解答43. Multiply Strings

LeetCode 43. Multiply Strings