Multiply Strings

Given two non-negative integersnum1andnum2represented as strings, return the product ofnum1andnum2.

这道题让我们求两个字符串数字的相乘,输入的两个数和返回的数都是以字符串格式储存的,这样做的原因可能是这样可以计算超大数相乘,可以不受int或long的数值范围的约束,那么我们该如何来计算乘法呢,我们小时候都学过多位数的乘法过程,都是每位相乘然后错位相加,那么这里就是用到这种方法.

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        result = [0]*(len(num1)+len(num2))
        pos = len(result)-1
        for n1 in reversed(num1):
            tempPos = pos
            for n2 in reversed(num2):
                result[tempPos] += int(n1)*int(n2)
                result[tempPos-1] += result[tempPos]/10  # carry
                result[tempPos] = result[tempPos]%10
                tempPos -= 1
            pos -= 1

        zeroIndex = 0
        while zeroIndex < len(result)-1 and result[zeroIndex] == 0:
            zeroIndex += 1

        return "".join(map(str, result[zeroIndex:]))

Last updated

Was this helpful?