leetcode

32 篇文章 0 订阅

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

Note:

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

思路:

1 翻转string

2 建立数组,双层循环遍历两个string,把单位的乘积累加到数组相应的位置

3 处理进位并输出

4 再把结果翻转

5 注意前导零的corner case


class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1.size()==0 || num2.size()==0)
            return string();
        if(num1=="0" || num2=="0")
            return "0";
            
        reverse(num1.begin(),num1.end());
        reverse(num2.begin(),num2.end());
        
        int n1 = num1.size();
        int n2 = num2.size();
        
        int d[n1+n2] = {0};
        
        for(int i=0;i<n1;i++)
        {
            for(int j =0;j<n2;j++)
            {
                d[i+j] += (num1[i]-'0') * (num2[j]-'0');         
            }
        }
        
        string res;
        for(int i=0;i<n1+n2;i++)
        {
            int digit = d[i]%10;
            int carry = d[i]/10;
            if(i+1<n1+n2)
                d[i+1] += carry;
            res.push_back(digit+'0');
        }
        
        
        reverse(res.begin(),res.end());
        int i=0;
        while(res[i]=='0')
        {
            i++;
        }
        string res1 = res.substr(i,res.size());
        return res1;
    }
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值