标签:
题目来源
https://leetcode.com/problems/multiply-strings/
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.
题意分析
Input: two numbers expressed as string
Output:the multiply of the two sums
Conditions:数可以无限大,做两个数的乘法
如:"23650379502752" 和 "865382861454"
结果:"20466633088564555427721408"
题目思路
首先将两个str转化为整数的list,然后考虑到乘积的位数必然小于等于len(str1)+len(str2),先初始化乘积为0的list,然后按照位数相乘的规律去做
注意:
1 最后结果需要将大数的0去掉,同时如果结果为0需要返回串“0”
2 翻转:mul.reverse()
AC代码(Python)
1 _author_ = "YE" 2 # -*- coding:utf-8 -*- 3 4 class Solution(object): 5 def multiply(self, num1, num2): 6 """ 7 :type num1: str 8 :type num2: str 9 :rtype: str 10 """ 11 len1 = len(num1) 12 len2 = len(num2) 13 14 list1 = [0 for i in range(len1)] 15 list2 = [0 for i in range(len2)] 16 17 for i in range(len1): 18 list1[len1 - 1 - i] = int(num1[i]) 19 for i in range(len2): 20 list2[len2 - 1 -i] = int(num2[i]) 21 22 # print(list1,list2) 23 24 mul = [0 for i in range(len1 + len2)] 25 26 for i in range(len2): 27 carry = 0 28 for j in range(len1): 29 mul[i + j] = mul[i + j] + carry + (list2[i] * list1[j]) % 10 30 31 carry = (list2[i] * list1[j]) // 10 32 33 if mul[i + j] >= 10: 34 carry = carry + mul[i + j] // 10 35 mul[i + j] = mul[i + j] % 10 36 37 38 if carry > 0: 39 mul[i + len1] += carry 40 if mul[i + len1] > 10: 41 mul[i + len1] = mul[i + len1] % 10 42 carry += mul[i + len1] // 10 43 44 index = len1 + len2 - 1 45 while index >= 0: 46 if mul[index] > 0: 47 break 48 index -= 1 49 50 if index + 1 < len1 + len2: 51 mul[index+1:] = [] 52 53 mul.reverse() 54 55 s = ‘‘ 56 for i in range(len(mul)): 57 s += str(mul[i]) 58 if s == ‘‘: 59 s = ‘0‘ 60 return s 61 62 str1 = ‘12312‘ 63 str2 = ‘4234‘ 64 s = Solution() 65 66 print(s.multiply(str1,str2))
[LeetCode]题解(python):043-Multiply Strings
标签:
原文地址:http://www.cnblogs.com/loadofleaf/p/5043205.html