【Leetcode_总结】43. 字符串相乘 -python

Q:

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

示例 1:

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

示例 2:

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

思路与字符串相加一样,先转成整形相乘在转字符串输出,代码如下:

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

    def str2int(self, s):
        s = s[::-1]
        num = 0
        for i, v in enumerate(s):
            offset = ord(v) - ord('0')
            num += offset * (10 ** i)
        return num

 【Leetcode_总结】43. 字符串相乘 -python

简单的办法如下,但是题目中要求不能使用内置函数,所以这些方法有待商榷

执行用时为 48 ms 的范例
class Solution:
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        return str(int(num1)*int(num2))