Question: https://oj.leetcode.com/problems/multiply-strings/
Question Name: Multiply Strings
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Solution: # @param num1, a string # @param num2, a string # @return a string def multiply(self, num1, num2): # Handle with the special case that, at least of the input is 0. if num1 == "0" or num2 == "0": return "0" result = [0] * (len(num1) + len(num2)) num1 = [int(i) for i in num1] num2 = [int(i) for i in num2] for index1 in xrange(len(num1)): multiplier = num1[index1] temp = [i*multiplier for i in num2] # Multiply temp.extend([0] * (len(num1) - index1 - 1)) # Shift # Add to the final result for resIndex in xrange(1, len(temp) + 1): result[-resIndex] += temp[-resIndex] # Normalize the final result. # We do not need to consider the first element. # For a m-length integer multiply n-length integer, the result # is at most with length of m+n. Thus the first element in array # "result" will never be more than 9. for resIndex in xrange(len(result)-1, 0, -1): result[resIndex-1] += result[resIndex] // 10 result[resIndex] %= 10 # Convert the final result into string result = "".join([str(i) for i in result]).lstrip("0") return result |