Skip to content

Latest commit

 

History

History
105 lines (76 loc) · 2.81 KB

0043._multiply_strings.md

File metadata and controls

105 lines (76 loc) · 2.81 KB

43. Multiply Strings

难度: Medium

刷题内容

原题连接

内容描述

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"
Note:

The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(1)******

直接一位一位的搞,最后转string, 但是考虑到这样kennel最后str2int(num1) * str2int(num2)是一个极大的数字可能会导致溢出,所以有了后面的思路2

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        def str2int(num):
            res = 0
            for i in range(len(num)-1, -1, -1):
                res += int(num[i]) * pow(10, len(num)-1-i)
            return res
        return str(str2int(num1) * str2int(num2))

思路 2 - 时间复杂度: O(N)- 空间复杂度: O(1)******

参考了别人的思路:

  1. m位的数字乘以n位的数字的结果最大为m+n位:
    • 99999 < 1000100 = 100000,最多为3+2 = 5位数。
  2. 先将字符串逆序便于从最低位开始计算。
class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        lookup = {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9} # 节省查找时间,避免无休止使用ord函数来得到数字
        if num1 == '0' or num2 == '0':
            return '0'
        num1, num2 = num1[::-1], num2[::-1]
        
        tmp_res = [0 for i in range(len(num1)+len(num2))]
        for i in range(len(num1)):
            for j in range(len(num2)):
                tmp_res[i+j] += lookup[num1[i]] * lookup[num2[j]]

        res = [0 for i in range(len(num1)+len(num2))]
        for i in range(len(num1)+len(num2)):
            res[i] = tmp_res[i] % 10
            if i < len(num1)+len(num2)-1:
                tmp_res[i+1] += tmp_res[i]/10 
        return ''.join(str(i) for i in res[::-1]).lstrip('0')  # 去掉最终结果头部可能存在的‘0’

觉得这样写才是最容易理解的,看一个具体的🌰:

input: num1, num2 = '91', '91'
tmp_res = [1,18,81,0]
res = [1,8,2,8]

最终返回 "8281"

要注意最终返回头部可能会有‘0’,所以我们用lstrip去除一下