标签:string ati inpu ems ref set store sel its
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:
num1
and num2
is < 110.num1
and num2
contains only digits 0-9
.num1
and num2
does not contain any leading zero.
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)
标签:string ati inpu ems ref set store sel its
原文地址:http://www.cnblogs.com/prmlab/p/7140820.html