43. Multiply Strings leetcode python 2016 new season

Total Accepted: 51879  Total Submissions: 231091  Difficulty: Medium

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

Show Company Tags
Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        num1_len = len(num1)
        num2_len = len(num2)
        arr = [0 for _ in range(num1_len + num2_len)]
        num1 = num1[::-1]
        num2 = num2[::-1]
        result = []
        for i in range(num1_len):
            for j in range(num2_len):
                arr[i + j] += int(num1[i]) * int(num2[j])
        for arr_i in range(num1_len + num2_len):
            digit = arr[arr_i] % 10
            carry = arr[arr_i] / 10
            if arr_i < num1_len + num2_len - 1:
                arr[arr_i + 1] += carry
            result.append(str(digit))
        result.reverse()
        while result[0] == '0' and len(result) > 1:
            del result[0]
        return "".join(result)


你可能感兴趣的:(43. Multiply Strings leetcode python 2016 new season)