11-2:(43)字符串相乘

43. 字符串相乘

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

示例 1:

输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:

输入: num1 = "123", num2 = "456"
输出: "56088"
说明:

  1. num1 和 num2 的长度小于110。

  2. num1 和 num2 只包含数字 0-9。

  3. num1 和 num2 均不以零开头,除非是数字 0 本身。

  4. 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。

Python most votes solution with some correction:

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        product = [0] * (len(num1) + len(num2))
        position = len(product)-1

        for n1 in reversed(num1):
            tempPos = position
            for n2 in reversed(num2):
                product[tempPos] += int(n1) * int(n2)
                product[tempPos-1] += product[tempPos] // 10
                product[tempPos] %= 10
                tempPos -= 1
            position -= 1

        pointer = 0
        while pointer < len(product)-1 and product[pointer] == 0:
            pointer += 1

        return ''.join(map(str, product[pointer:]))

分析:

(1)该算法其实就是在模仿小学乘法步骤,示例如下:

假设 n1 = 1234,n2 = 5678,则

      5 6 7 8
    x 1 2 3 4
-----------------
    2 2 7 1 2
  1 7 0 3 4
1 1 3 5 6
5 6 7 8
-----------------
7 0 0 6 6 5 2

每次都仅是一位数字与一位数字相乘。

(2)注意到两个多位数相乘,乘积的位数一定不会多于这两个多位数的位数之和。

(3)代码的pointer部分是为了消除乘积前面多于的0。(因为预先申请存储空间时把乘积的所有位都置成了0)。

(4)最后一行代码提供了将列表转换成字符串的一种方法:

假设nums是列表,则可通过如下代码将其转换成一个字符串:

nums = ''.join(map(str, nums))
原文地址:https://www.cnblogs.com/tbgatgb/p/11164384.html