leetcode

题目描述

 

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.

class Solution {

public:

    string multiply(string num1,string num2)

    {

        int n=num1.size();

         int m=num2.size();

         if(n==0||m==0)

              return "";

        string result="";

        long long k=toi(num2);

        if(k==1)

            return num1;

        if(k==0||toi(num1)==0)

            return "0";

        vector<string> rd;

        int kf=0;

        for(int i=m-1;i>=0;i--)

        {

         string s=""+string(kf++,'0');

         int s2=0;

         int k2=num2[i]-48;

         for(int j=n-1;j>=0;j--)

            {

                 int k1=num1[j]-48;

                 s+=char(((k1*k2)+s2)%10+48);

                 s2=((k1*k2)+s2)/10;

            }

        if(s2!=0)

        s+=char(s2+48);

        reverse(s.begin(),s.end());

        rd.push_back(s);

        }

        for(int i=0;i<rd.size();i++)

        {

            result=multiply_k(rd[i], result);

        }

        return result;

    }

    long long toi(string num2)

    {

        long long result=0;

        int n=num2.size();

        int s=1;

        result+=num2[n-1]-48;

        for(int i=n-2;i>=0;i--)

        {

            s*=10;

            result+=(num2[i]-48)*s;

        }

        return result;

    }

    string multiply_k(string num1, string num2)

    {

          int s=0;

          string result="";

          int n=num1.size();

          int m=num2.size();

          if(m==0)

              return num1;

          if(n==0)

              return num2;

          int i=n-1,j=m-1;

          while(i>=0&&j>=0)

          {

               vector<int> k;

               f(num1[i]-48,num2[j]-48,s,k);

               s=k[0];

               result+=char(k[1]+48);

               i--;

               j--;

          }

          while(i>=0)

          {

              int kf=num1[i]+s-48;

              s=kf/10;

              result+=char(kf%10+48);

              i--;

          }

          while(j>=0)

          {

              int kf=num2[j]+s-48;

              s=kf/10;

              result+=char(kf%10+48);

              j--;

          }

         if(s!=0)

         result+=char(s+48);

        reverse(result.begin(),result.end());

        return result;

    }

    void f(int i,int j,int s,vector<int>&fd)

    {

        int result=i+j+s;

        fd.push_back(result/10);

        fd.push_back(result%10);

    }

};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值