leetcode: 43. Multiply Strings

来源:互联网 发布:阿里云 redis qps 编辑:程序博客网 时间:2024/06/15 19:08

Q

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

The length of both num1 and num2 is < 110.Both num1 and num2 contains only digits 0-9.Both num1 and num2 does not contain any leading zero.You must not use any built-in BigInteger library or convert the inputs to integer directly.

AC

# Time:  O(m * n)# Space: O(m + n)class Solution(object):    def multiply(self, num1, num2):        """        :type num1: str        :type num2: str        :rtype: str        """        num1, num2 = num1[::-1], num2[::-1]        res = [0] * (len(num1) + len(num2))        for i in xrange(len(num1)):            for j in xrange(len(num2)):                res[i + j] += int(num1[i]) * int(num2[j])                res[i + j + 1] += res[i + j] / 10                res[i + j] %= 10        i = len(res) - 1        while i > 0 and res[i] == 0:            i -= 1        return ''.join(map(str, res[i::-1]))# Time:  O(m * n)# Space: O(m + n)# Using built-in bignum solution.class Solution2(object):    def multiply(self, num1, num2):        """        :type num1: str        :type num2: str        :rtype: str        """        return str(int(num1) * int(num2))if __name__ == "__main__":    assert Solution().multiply("123", "1000") == '123000'