1. 程式人生 > >【Leetcode_總結】43. 字串相乘 -python

【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

 

簡單的辦法如下,但是題目中要求不能使用內建函式,所以這些方法有待商榷

執行用時為 48 ms 的範例
class Solution:
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        return str(int(num1)*int(num2))