Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
1 2
Input: num1 = "2", num2 = "3" Output: "6"
Example 2:
1 2
Input: num1 = "123", num2 = "456" Output: "56088"
Note:
The length of both num1 and num2 is < 110. Both num1 and num2 contain only digits 0-9. Both num1 and num2 do not contain any leading zero, except the number 0 itself. You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution:
Things to note:
The product of two numbers cannot exceed the sum of the two lengths. (e.g. 99 * 99 cannot be five digit)
classSolution: defmultiply(self, num1: str, num2: str) -> str: m, n = len(num1), len(num2) result = [0] * (m + n) for i in range(m - 1, -1, -1): for j in range(n - 1, -1, -1): mul = (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0')) posLow = i + j + 1 posHigh = i + j mul += result[posLow] result[posLow] = mul % 10 result[posHigh] += mul // 10 # e.g., num1='123', num2='456'; then result = [0, 5, 6, 0, 8, 8], res = [5, 6, 0, 8, 8] print(result) sb = [] for res in result: print(res) if len(sb) != 0or res != 0: # deal with leading zero issue sb.append(res) print(sb) print("------") return"0"if len(sb) == 0else''.join(str(s) for s in sb)