Leetcode43 大数相乘 Python版

今天刷leetcode的时候,刷到了一道大数相乘的题目,以前水比赛的时候都是模板或者java。。今天算是第一次写大数相乘的题目了。

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

一开始思路很弱智,将一个数从低位开始按位取,乘上另一个数,然后一层一层的叠加起来,结果没错,就是超时了,上一下超时的代码:

#encoding=utf-8
import numpy as np


class Solution(object):
    def mul(self, num1, num2, base, length):
        c = 0
        l = ['0']*300
        top = 299 - base
        index = len(num1)-1
        n2 = int(num2)
        while index>=0 or c != 0:
            if index >= 0:
                l[top] = str((n2*int(num1[index])+c) % 10)
                c = (n2*int(num1[index])+c) / 10
            elif c != 0:
                l[top] = str(c)
                c = 0
            index -= 1
            top -= 1
        return l

    def add(self, num1, num2, length):
        l = ['0']*300
        c = 0
        top = 299
        while top>=0:
            l[top] = str((int(num1[top])+int(num2[top])+c)%10)
            c = (int(num1[top])+int(num2[top])+c)/10
            top -= 1
        return l


    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        if num1 == '0' or num2 == '0':
            return '0'
        if len(num2) > len(num1):
            tmp = num2
            num2 = num1
            num1 = tmp
        length =len(num1) + len(num2) + 1
        top = len(num2)-1
        base = 0
        ans = ['0']*300
        while top >= 0:
            ans = self.add(ans, self.mul(num1, num2[top], base, length), length)
            top -= 1
            base += 1
        ans_str = ''.join(ans)
        index = 0
        while index < len(ans_str):
            if ans_str[index] != '0':
                break
            index += 1
        return ans_str[index:]

然后才发现,可以一次性全都按位乘出结果,不考虑进位,再一次性处理进位。然后就解决超时问题了。

上个代码:

#encoding=utf-8
import numpy as np


class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        if num1 == '0' or num2 == '0':
            return '0'
        length =len(num1) + len(num2) + 1
        l = [0] * length
        l_1 = list(num1)
        l_2 = list(num2)
        l_1.reverse()
        l_2.reverse()
        for i in range(len(l_2)):
            for j in range(len(l_1)):
                l[i+j] += int(l_2[i])*int(l_1[j])
        c = 0
        for i in range(length):
            tmp = l[i] + c
            c = tmp / 10
            l[i] = tmp % 10
        l.reverse()
        ans = []
        flag = False
        for i in range(length):
            if flag == False and l[i] == 0:
                continue
            else:
                flag = True
                ans.append(str(l[i]))
        return ''.join(ans)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值