[Leetcode]43. Multiply Strings @python

题目

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.

题目要求

给定两个用字符串表示的数字,进行乘法运算,并且返回结果用字符串表示。

解题思路

先将两个数字字符串进行反转,使得低位在前,然后根据乘法法则逐位相乘,并将结果先累加到相应位置上,然后对逐位乘的结果按位从低位到高位取模,进位。最后返回时要先去掉高位可能存在的0。

代码

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        # make sure size of num2 is bigger than size of num1
        if len(num1) > len(num2):
            return self.multiply(num2,num1)
        num1 = num1[::-1]
        num2 = num2[::-1]
        ans = [0] * (len(num1) + len(num2))

        for i in range(len(num1)):
            for j in range(len(num2)):
                ans[i + j] += int(num1[i]) * int(num2[j])
        c = 0
        for i in range(len(ans)):
            ans[i] += c
            ans[i],c = ans[i] % 10, ans[i] / 10
        while c > 0:
            ans.append(c % 10)
            c = c / 10
        index = len(ans) - 1
        while index > 0 and ans[index] == 0:
            index -= 1
        return ''.join([str(x) for x in ans[0:index + 1]][::-1])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值