leetcode_[python/C++逐步深入] 43. Multiply Strings_(大数乘法分析)

本篇博客详细分析了LeetCode 43题——大数乘法的解决方案,禁止直接将字符串转换为整数。文中展示了Python利用reduce高效解决方法,以及C++通过翻转数字进行O(mn)复杂度的乘法运算。还探讨了不翻转数字和按位计算的其他思路。
摘要由CSDN通过智能技术生成

题目链接
【题目】
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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.


【分析】
先看下python的写法:
使用reduce是及其简便的写法,而且效率很高

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        num1 = reduce(lambda x, y: x * 10 + y, [ord(i) - 48 for i in num1]) # '0' is 48 in ascii
        num2 = reduce(lambda x, y: x * 10 + y, [ord(i) - 48 for i in num2])
        return str(num1 * num2)

打败了95%
这里的[ord(i) - 48 for i in num]可以改写成map形式,会快那么一点点

class 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值