[leetcode] 43. Multiply Strings

556 篇文章 2 订阅
441 篇文章 0 订阅

Description

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

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

分析

题目的意思是:求两个数字字符串的乘积。

  • 把错位相加后的结果保存到一个一维数组中,然后分别在每位上算进位,最后每个数字都变成一位,然后要做的是去除掉首位0,最后把每位上的数字按顺序保存到结果中即可

C++ 代码

class Solution {
public:
    string multiply(string num1, string num2) {
        string res="";
        int m=num1.size();
        int n=num2.size();
        vector<int> v(m+n,0);
        int k=m+n-2;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                v[k-i-j]+=(num1[i]-'0')*(num2[j]-'0');
            }
        }
        int carry=0;
        for(int i=0;i<m+n;i++){
            v[i]+=carry;
            carry=v[i]/10;
            v[i]=v[i]%10;
        }
        int i=m+n-1;
        while(v[i]==0){
            i--;
        }
        if(i<0){
            return "0";
        }
        while(i>=0) res.push_back(v[i--]+'0');
        return res;
    }
};

Python 代码

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        res=0
        m=len(num1)
        n=len(num2)
        res=[0]*(m+n)
        k=m+n-2
        for i in range(m):
            for j in range(n):
                res[k-i-j]+=int(num1[i])*int(num2[j])
        carry=0
        for i in range(m+n):
            res[i]+=carry
            carry=res[i]//10
            res[i]=res[i]%10
        
        i=m+n-1
        while i>=0 and res[i]==0:
            i-=1
        res=[str(item) for item in res]
        if i<0:
            return '0'
        return ''.join(reversed(res[:i+1]))

参考文献

[编程题]multiply-strings
[LeetCode] Multiply Strings 字符串相乘

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值