leedcode解析—Python3—Multiply Strings—medium

该博客介绍了一种不使用内置大数库或直接转换为整数的方法来计算两个非负整数字符串的乘积。博主提供了一个Python类解决方案,通过自定义函数将字符串转换为整数,然后进行乘法运算,最后返回乘积字符串。这种方法在时间和空间效率上有一定的优势。

题目:
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

我的思路:
题目非常简单,计算两个字符串代表数字的乘积,不能使用int(),可以直接用一个字典来给出字符串不同位置代表的数值,Runtime: 28 ms(约93.57%);Memory Usage: 14.3 MB(约26.59%),复杂度O(len(num1)+len(num2))

我的解答:

class Solution:    
    def multiply(self, num1: str, num2: str) -> str:
        def my_int(a: str):
            my_dic = {str(i): i for i in range(10)}
            ans = 0
            for i in range(len(a)):
                ans += my_dic[a[i]] * 10**(len(a) - i - 1)
            return ans
              
        return str((my_int(num1)) * (my_int(num2)))

答案:

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值