大数乘法

#include
#include
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, 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);
}
MData::~MData()
{
    if(str1!=nullptr)
        delete[] str1;
    if(str2!=nullptr)
        delete[] str2;
}
char* MData::GetSum()
{
    //cout<
    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
//    {
//        cout<
//    }
    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;
}
 
  
 
 

你可能感兴趣的:(C++)