LeetCode Multiply Strings
LeetCode-solving Multiply Strings
Original question
Multiply two numbers represented by strings and return the string results.
Note:
The given number is a non-negative integer and can be infinite.
Example:
Input: num1 = "123", num2 = "20"
Output: "2460"
Solutions
According to the formula of multiplication, the multiplication operation is actually to perform the multiplication operation on each bit first, and then perform the addition operation on all results. First, specify that the number of m-bit multiplied by the number of n-bit is mostly m + n-bit (when all are 9 ). The numbers equal to 0 are aligned at the end when they are added. For example, 123 × 456, we can see that 1 × 6, 2 × 5, and 3 × 4 are aligned at the end of addition, we can add these numbers in the first round of multiplication, and the following zeros are represented by positions in the list. Use a loop to carry out the carry addition, and finally remove the excess 0 at the beginning. For detailed steps, see the following example:
123*456100 400 20 50 3 6[3*6, 2*6+3*5, 1*6+2*5+3*4, 2*4+1*5, 1*4, 0][18, 27, 28, 13, 4, 0][8, 27+1, 28, 13, 4, 0][8, 8, 28+2, 13, 4, 0][8, 8, 0, 13+3, 4, 0][8, 8, 0, 6, 5, 0]"880650"-->"056088""56088"
AC Source Code
class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ num1 = num1[::-1] num2 = num2[::-1] length1 = len(num1) length2 = len(num2) temp = [0 for __ in range(length1 + length2)] # Do multiply for i in range(length1): for j in range(length2): temp[i + j] += int(num1[i]) * int(num2[j]) carry = 0 digits = [] # Do plus for num in temp: s = carry + num carry = s // 10 digits.append(str(s % 10)) result = "".join(digits)[::-1] # Remove the surplus zero sub_index = 0 for i in range(length1 + length2 - 1): if result[i] == "0": sub_index += 1 else: break result = result[sub_index:] return resultif __name__ == "__main__": assert Solution().multiply("120", "20000") == 2400000 assert Solution().multiply("0", "3421") == 0
Please check out my Github for relevant source code.