Multiply Strings

Question

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

Note:

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

Tags

  • Maths
  • String

Thought

Reference: https://discuss.leetcode.com/topic/20883/simple-python-solution-18-lines/3

Use the list to store the product between the digits of two numbers.

Code

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        res = [0 for _ in xrange(len(num1) + len(num2))] 
        for i, digit1 in enumerate(reversed(num1)):
            for j, digit2 in enumerate(reversed(num2)):
                res[i + j] += int(digit1) * int(digit2)
                res[i + j + 1] += res[i + j] / 10
                res[i + j] %= 10
        while len(res) > 1 and res[-1] == 0:
            res.pop()
        return ''.join(map(str, reversed(res)))

results matching ""

    No results matching ""