Leetcode 43: Multiply Strings 大数相乘算法

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

示例 2:

输入: num1 = "123", num2 = "456"
输出: "56088"
class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        num1=[int(i) for i in num1]
        num2=[int(i) for i in num2]
        ans = [0 for i in range(len(num1) + len(num2))]

        for i in range(len(num1))[::-1]:
            for j in range(len(num2))[::-1]:
                ans[i+j+1] += num1[i] * num2[j]
        for i in range(len(ans))[::-1]:
            if ans[i]>10:
                ans[i-1]+=ans[i]/10
                ans[i]=ans[i]%10
        tmp = 0
        for i in range(len(ans))[::-1]:
            tmp += ans[i] * 10 ** (len(ans) - i -1)
        return str(tmp)

a*b结果的最大长度是a和b的长度的和,先不考虑进位的问题,结果的每一位有这样的规律,结果的位是两个数相对位的和:

ans[i+j+1]=a[i]*a[j]

之后再对结果进行进位处理

参考

https://blog.csdn.net/u010983881/article/details/77503519

https://www.cnblogs.com/wmx24/p/9064134.html

 

你可能感兴趣的:(Leetcode)