LeetCode 43. 字符串相乘

2022-08-28  本文已影响0人  草莓桃子酪酪
题目

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数。

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

方法
class Solution(object):
    def multiply(self, num1, num2):
        if num1 == '0' or num2 == '0':
            return '0'
        
        m, n = len(num1), len(num2)
        result = [0] * (m+n)
        for i in range(m-1, -1, -1):
            for j in range(n-1, -1, -1):
                result[i+j+1] += int(num1[i]) * int(num2[j])
        
        for i in range(m+n-1, 0, -1):
            result[i-1] += result[i] // 10
            result[i] %= 10

        if result[0] == 0:
            return ''.join(str(i) for i in result[1:])
        else:
            return ''.join(str(i) for i in result) 
报错
参考

代码相关:https://leetcode.cn/problems/multiply-strings/solution/zi-fu-chuan-xiang-cheng-by-leetcode-solution/
报错:https://stackoverflow.com/questions/10880813/typeerror-sequence-item-0-expected-string-int-found

上一篇 下一篇

猜你喜欢

热点阅读