Hilavergil的博客

你不认识我

leetcode--43. 字符串相乘

题目:43. 字符串相乘

链接:https://leetcode-cn.com/problems/multiply-strings/description/

模拟大整数乘法,给定的两个乘数为字符串格式。

python:

def myMulti(num1,num2):
    if num2[0]=="0" or num1[0]=="0":
        return "0"
    res,add="",0
    for i in range(len(num1)-1,-1,-1):
        temp=int(num1[i])*int(num2)+add
        res+=(str)(temp%10)
        add=temp//10
        # num1.pop(-1)
    if add!=0:
        res+=(str)(add)
    return res[::-1]


def myAdd(num1,num2):
    if num1[0]=="0":
        return str(num2)
    if num2[0]=="0":
        return str(num1)
    res,add="",0
    i,j=len(num1)-1,len(num2)-1
    while i>=0 and j>=0:
        temp=int(num1[i])+int(num2[j])+add
        res+=(str)(temp%10)
        add=temp//10
        i-=1
        j-=1
    while i>=0:
        temp=int(num1[i])+add
        res+=(str)(temp%10)
        add=temp//10
        i-=1
    while j>=0:
        temp=int(num2[j])+add
        res+=str(temp%10)
        add=temp//10
        j-=1
    if add:
        res+=(str)(add)
    return res[::-1]
class Solution:
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        if num2[0] == "0" or num1[0] == "0":
            return "0"
        num2=list(num2)
        res,last,offset="","0",0
        while num2:
            res=str(myMulti(num1, num2[-1]))
            for i in range(offset):
                res+="0"
            res=str(myAdd(str(res),str(last)))
            offset+=1
            last=res
            num2.pop(-1)
        return res

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hilavergil/article/details/79966213
文章标签: leetcode python
个人分类: leetcode
上一篇leetcode--38. 数数并说
下一篇leetcode--44. 通配符匹配
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭