码迷,mamicode.com
首页 > 其他好文 > 详细

43. Multiply Strings

时间:2017-07-09 12:38:23      阅读:107      评论:0      收藏:0      [点我收藏+]

标签: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:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. 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

标签:string   ati   inpu   ems   ref   set   store   sel   its   

原文地址:http://www.cnblogs.com/prmlab/p/7140820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!