前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >字符串相乘

字符串相乘

作者头像
木又AI帮
发布2020-07-07 12:05:21
6250
发布2020-07-07 12:05:21
举报
文章被收录于专栏:木又AI帮木又AI帮

题目:43. 字符串相乘

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

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。 示例 1: 输入: num1 = "2", num2 = "3" 输出: "6" 示例 2: 输入: num1 = "123", num2 = "456" 输出: "56088" 说明: num1 和 num2 的长度小于110。 num1 和 num2 只包含数字 0-9。 num1 和 num2 均不以零开头,除非是数字 0 本身。 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。

解题:

1、str2每位数乘以str1,得到一个字符串结果,再将所有字符串结果相加。

代码:

代码语言:javascript
复制
class Solution(object):
    def multi(self, str1, s2):
        # 一位数乘以多位数
        add = 0
        res = ''
        for s1 in str1[::-1]:
            tmp = int(s1) * int(s2) + add
            res += str(tmp % 10)
            add = tmp // 10
        if add != 0:
            res += str(add)
        return res[::-1]


    def add(self, str1, str2):
        # 字符串相加
        add = 0
        if len(str1) > len(str2):
            str1, str2 = str2, str1

        i = 1
        res = ''
        while i <= len(str1):
            tmp = int(str1[-i]) + int(str2[-i]) + add
            res += str(tmp % 10)
            add = tmp // 10
            i += 1

        while i <= len(str2):
            tmp = int(int(str2[-i]) + add)
            res += str(tmp % 10)
            add = tmp // 10
            i += 1

        if add != 0:
            res += str(add)
        return res[::-1]



    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        if num1 == '0' or num2 == '0':
            return '0'

        res = []
        for i, s2 in enumerate(num2[::-1]):
            res.append(self.multi(num1, s2) + '0' * i)
        res = reduce(lambda x, y: self.add(x, y), res)
        return res
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档