43. Multiply Strings
Posted Premiumlab
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了43. Multiply Strings相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/multiply-strings/#/description
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Sol:
class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ # The key to this problem is that 1) reverse two strings 2) multiply them by digit 3) Store the result in an arrary rathan carry 4) Get the mode(%) of the array as interset it as a result digit. And the tenth (/10) of the array is the carry. num1 = num1[::-1] num2 = num2[::-1] # initilize arrary # The max length of the multiple of two numbers is the sum of the length of two numbers. arr = [0] * (len(num1) + len(num2)) for digit1 in range(len(num1)): for digit2 in range(len(num2)): arr[digit1 + digit2] += int(num1[digit1]) * int(num2[digit2]) ans = [] for i in range(len(arr)): digit_ans = arr[i] % 10 carry_ans = arr[i] /10 if i < len(arr) - 1: arr[i+1] += carry_ans # insert the digit of answer at position 0 ans.insert(0, str(digit_ans)) while ans[0] == "0" and len(ans) > 1: del ans[0] return ‘‘.join(ans)
以上是关于43. Multiply Strings的主要内容,如果未能解决你的问题,请参考以下文章