43. leetcode題目講解(Python):字符串相乘(Multiply Strings)

題目如下:

思路:

這道題值得注意的是,要求不能直接將string 轉換爲 int。

參考代碼:

class Solution:
    def str2num(self, num):
        int_num = 0
        pos = 1
        for n in num[::-1]:
            int_num += (ord(n) -  48) * pos
            pos = pos * 10
        print(int_num)
        return int_num

    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        n1 = self.str2num(num1)
        n2 = self.str2num(num2)
        return repr(n1 * n2)

源碼地址:
https://github.com/jediL/LeetCodeByPython

其它題目:[leetcode題目答案講解彙總(Python版 持續更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建議,歡迎交流 :-D,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章