175.(43)字符串相乘

题目描述:

给定两个以字符串形式表示的非负整数 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、将num2的每一个字符与num1相乘

2、将步骤1中每一个字符串按照乘积的格式进行相加

代码:

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1=="0"||num2=="0")
            return "0";
        vector<string>res;
        string s;
        int temp,product,sum;
        for(int i=num2.size()-1;i>=0;i--)
        {
            temp=0;
            s="";
            for(int j=num1.size()-1;j>=0;j--)
            {
                product=(num2[i]-'0')*(num1[j]-'0')+temp;
                temp=0;
                if(product>=10)
                {
                    temp=product/10;
                    product=product%10;
                }
                s+=to_string(product);
            }
            if(temp!=0)
                s+=to_string(temp);
            res.push_back(s);
        }
        for(int i=1;i<res.size();i++)
        {
            temp=0;
            s="";
            for(int j=0;j<res[i].size();j++)
            {
                if(j+i>=res[0].size())
                {
                    if(temp==1)
                    {
                        if(res[i][j]-'0'+temp>=10)
                        { 
                            s+=to_string((res[i][j]-'0'+temp)-10);
                            temp=(res[i][j]-'0'+temp)/10;
                        }
                        else
                        {
                             s+=to_string(res[i][j]-'0'+temp);
                             temp=0;
                        }
                    }
                    else
                        s+=res[i][j];
                }
                else 
                {
                    sum=(res[0][j+i]-'0')+(res[i][j]-'0')+temp;
                    temp=0;
                    if(sum>=10)
                    {
                        temp=1;
                        sum-=10;
                    }
                    res[0][j+i]=to_string(sum)[0];
                }
            }
            res[0]+=s;
            if(temp!=0)
                res[0]+=to_string(temp);
        }
        reverse(res[0].begin(),res[0].end());
        return res[0];
    }
};

执行效率:

执行用时:152 ms, 在所有 C++ 提交中击败了10.62%的用户

内存消耗:8 MB, 在所有 C++ 提交中击败了39.82%的用户

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值