LeetCode-43 字符串相乘

2019-02-28  本文已影响0人  FlyCharles

1. 题目

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

示例 1:

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

示例 2:

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

说明:


2. 我的AC

方法一

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        return str(int(num1) * int(num2))

方法二:大整数乘法

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        num1 = num1[::-1]
        num2 = num2[::-1]
        length1 = len(num1)
        length2 = len(num2)
        temp = [0] * (length1 + length2)
        for i in range(length1):
            for j in range(length2):  
                temp[i+j] += int(num1[i]) * int(num2[j])
    
        result = []
        for i, num in enumerate(temp):
            digit = num % 10
            carry = num / 10 
            result.insert(0, str(digit))
            if i < length1 + length2 - 1:
                temp[i+1] += carry
        while result[0] == '0' and len(result) > 1: # "9133" * "0"
            result.pop(0)   
        return "".join(result)

3. 小结

  1. 删除列表第0位
result.pop(0)   
上一篇 下一篇

猜你喜欢

热点阅读