微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

大数乘法

#include <iostream>
#include<cstring>
using namespace std;
 
class MData
{
 private:
    int n,m;
    char *str1,*str2;
 public:
    char *GetSum();
    MData();
    MData(const char *s1,const char * s2);
    void init(const char *s1,const char * s2);
    ~MData();
 
};
 
MData::MData()
{
    str1=nullptr;
    str2 = nullptr;
    n = 0;
    m = 0;
}
MData::MData(const char *s1, const char *s2)
{
    n = (int)strlen(s1);
    m = (int)strlen(s2);
    str1 = new char[n+1]{'\0'};
    str2 = new char[m+1]{'\0'};
    strcpy(this->str1,s1);
    strcpy(this->str2,s2);
}
void MData::init(const char *s1,s2);
}
MData::~MData()
{
    if(str1!=nullptr)
        delete[] str1;
    if(str2!=nullptr)
        delete[] str2;
}
char* MData::GetSum()
{
    //cout<<str1<<endl<<str2<<endl<<n<<endl<<m<<endl;
    int *s = new int[n+m];
    for(int i = 0;i<n+m;i++)
    {
        s[i] = 0;
    }
    for(int i = 0;i<n;i++)
        for(int k = 0;k<m;k++)
        {
            s[i+k+1] += (str1[i]-'0')*(str2[k]-'0');
        }
//    for(int i = 0;i<n+m;i++)
//    {
//        cout<<s[i]<<endl;
//    }
    for(int i = n+m-1;i>=0;i--)
    {
        if(s[i]>=10)
        {
            s[i-1] += s[i]/10;
            s[i] %= 10;
        }
    }
    int i = 0;
    while(s[i] == 0)
    {
        i++;
    }
    char *sum = new char[n+m-i+1]{'\0'};
    int k = 0;
    int kn = n+m-i+1;
    for(;k<kn&&i<n+m;k++,i++)
    {
        sum[k] = s[i]+'0';
    }
    sum[k] = '\0';
    delete[] s;
    return sum;
}
int main()
{
    char *str1=new char[100]{'\0'},*str2=new char[100]{'\0'};
    cin>>str1;
    cin>>str2;
    MData sk(str1,str2);
    char *fk = sk.GetSum();
    cout << fk << endl;
    delete[]str1;
    delete[]str2;
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐