Leetcode: Multiply Strings

本文介绍了一种处理任意大小整数相乘的方法,并提供了一个详细的Python实现案例。该算法将输入的字符串形式的大整数转换为数字进行计算,再将结果转换回字符串输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

Hide Tags Math String
Hide Similar Problems (M) Add Two Numbers (E) Plus One (E) Add Binary


Solution

Get idea from here1, here2

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """

        if len(num1)==0 or len(num2)==0 or num1=='0' or num2=='0':
            return '0'

        num1, num2 = list(num1), list(num2)
        num1.reverse()
        num2.reverse()

        res = [0]*(len(num1)+len(num2))
        for ind1 in range(len(num1)):
            a = ord(num1[ind1]) - ord('0')
            for ind2 in range(len(num2)):
                b = ord(num2[ind2]) - ord('0')
                res[ind1+ind2] += a*b

        ress = []
        carry = 0
        for ind in range(len(res)):
            digit = res[ind]%10
            ress = [(digit+carry)%10] + ress
            carry = res[ind]/10 + (digit+carry)/10


        if len(ress)>0 and ress[0]==0:
            ress = ress[1:]

        ress = [str(elem) for elem in ress]
        ress = ''.join(ress)

        return ress       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值