zoukankan      html  css  js  c++  java
  • 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:

    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)
            
  • 相关阅读:
    java的原子类 AtomicInteger 实现原理是什么?
    Tomcat性能调优
    JVM性能调优
    vue下载和上传excle数据文件,解析excel文件数据并存在数据库中
    07----popo up 弹窗
    06----fiter
    05 ---批量操作
    04
    stark组件03
    stack组件03
  • 原文地址:https://www.cnblogs.com/prmlab/p/7140820.html
Copyright © 2011-2022 走看看