字符串乘积

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.

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1.size()>110 || num2.size()>110) return 0;
        if(num1.empty() || num2.empty() ) return 0;
        string result;
        for(int i=num2.size()-1;i>=0;i--){
            int carry=0;
            int numi= num2[i]-'0';
            string solution;
            for(int j=num1.size()-1;j>=0;j--){
                int numj=num1[j]-'0';
                int multi=(numi*numj+carry)%10;
                carry=(numi*numj+carry)/10;
                solution.insert(solution.begin(),multi+'0');
            }
            if(carry!=0) solution.insert(solution.begin(),carry+'0');
            for(int j=num2.size()-1;j>i;j--) solution.push_back('0');
            result=add(result,solution);
        }
        size_t start=0;
        while(result[start] == '0' && start < result.size()-1){
            start++;
        }
        return result.substr(start, result.size());
    }
    string add(string a,string b){
     int carry=0;
     string result;
     for(int i=a.size()-1,j=b.size()-1; i>=0||j>=0; i--,j--){
         int ai= i>=0?a[i]-'0':0;
         int bj= j>=0?b[j]-'0':0;
         int val=(ai+bj+carry)%10;
         carry=(ai+bj+carry)/10;
         result.insert(result.begin(),val+'0');
     }
     if(carry==1)
         result.insert(result.begin(),'1');
     return result;
 }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值