[LeetCode]题解(python):043-Multiply Strings
题目来源:
https://leetcode.com/problems/multiply-strings/
题意分析:
实现一个非负整数的大数相乘。
题目思路:
做这题的时候本来我是打算将两个数拆成ab * cd的,但是用ptyhon实现的时候超时了,而用C同样的思想过是没有问题的。后来还是规规矩矩的用每个数拆开相乘。这是的时间复杂度是O(m*n)。
代码(python):
1 class Solution(object): 2 def multiply(self, num1, num2): 3 """ 4 :type num1: str 5 :type num2: str 6 :rtype: str 7 """ 8 size1 = len(num1);size2 = len(num2) 9 if size1 <= 5 and size2 <= 5: 10 tmp = int(num1) * int(num2) 11 return str(tmp) 12 num1 = num1[::-1];num2 = num2[::-1] 13 array = [0 for i in range(len(num1) + len(num2))] 14 for i in range(len(num1)): 15 for j in range(len(num2)): 16 array[i + j] += int(num1[i]) * int(num2[j]) 17 ans = [] 18 for i in range(len(array)): 19 digit = array[i] % 10 20 carry = array[i] / 10 21 if i < len(array) - 1: 22 array[i + 1] += carry 23 ans.insert(0,str(digit)) 24 while ans[0] == '0' and len(ans) > 1: 25 del ans[0] 26 return ''.join(ans)
转载请注明出处:http://www.cnblogs.com/chruny/p/4934403.html