Leetcode 43. Multiply Strings (python+cpp)

博客介绍了LeetCode 43题——Multiply Strings的解法,包括两种思路,一种利用当前数字位置计算乘积,另一种在二刷时提出更直观的逻辑方法,避免了整数与字符转换的过程。还提到了相关字符串运算的补充阅读材料。
摘要由CSDN通过智能技术生成

题目

在这里插入图片描述

解法:

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if num1 == '0' or num2 == '0':
            return '0'
        # initialize the product as a list, the length of the product of these two num won't exceed the sum of length of num1 and num2
        product = [0] * (len(num1) + len(num2))
        # initialize the operation position, starting from the end of the product list
        pos = len(product) - 1
        for n1 in reversed(num1):
            # store the position for multiplying a single char in num1 with the entire num2
            curr_pos = pos
            for n2 in reversed(num2):
                # add the results at corresponding position
                product[curr_pos] += (ord(n1) - ord('0')) * (ord(n2) - ord('0'))
                # take care of the carry
                product[curr_pos - 1] += product[curr_pos] // 10
                product[curr_pos] %= 10
                curr_pos -= 1
            pos -= 1
        ans = ''
        # removed the starting 0s
        i = 0
        while i < len
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值