高精度计算 大数乘法

#include 
#include 

using std::cin;
using std::cout;
using std::endl;

char *multiplication( char *s1, char *s2 );
int check( int *a, int n );//进位,去零,返回去零后的长度
int *StrToInt(char *str);//将逆序字符串并转换成整型数组
char *IntToStr( int *a, int n );//逆序整型数组并转换成字符串

int main()
{
    char s1[100000],s2[100000];
    //cin >> s1 >> s2;
    while ( cin >> s1 >> s2 )
        cout << multiplication(s1,s2) << endl;

    return 0;
}



char *multiplication( char *s1, char *s2 )
{
    int len1 = strlen(s1), len2 = strlen(s2);
    int len = len1 + len2;

    int *t1 = new int [len1];
    int *t2 = new int [len2];
    int *t  = new int [len]();
    t1 = StrToInt(s1);    t2 = StrToInt(s2);

    int i = 0, j = 0;
    for ( i = 0; i != len1; ++i )
        for ( j = 0; j != len2; ++j )
            t[i + j] += t1[i]*t2[j];

    len = check(t, len);

    return IntToStr(t, len);

}

//将逆序字符串并转换成整型数组
int *StrToInt(char *str)
{
    int len = strlen(str);
    int *a = new int [len];
    for ( int i = 0; i != len; ++i )
        a[i] = str[len - i - 1] - '0';
    return a;
}

//逆序整型数组并转换成字符串
char *IntToStr( int *a, int n )
{
    char *str = new char [n + 1];

    for ( int i = 0; i != n; ++i )
        str[i] = a[n - i - 1] + '0';

    str[n] = '\0';
    return str;
}

//进位,去零,返回去零后的长度
int check( int *a, int n )
{
    int i = 0;
    for ( i = 0; i != n; ++i ){
        if ( a[i] > 9 ){
            a[i + 1] = a[i + 1] + a[i]/10;
            a[i] %= 10;
        }
    }

    while ( 0 == a[n - 1] && n > 1 )
        --n;

    return n;
}
/**优化过的函数,更加精简。
int *Str2Int( char *s ){
    int len = strlen(s);
    int *a = new int [len];

    int i(0);
    while ( i != len )
        a[i++] = s[len - 1 - i] - '0';

    return a;
}

char *Int2Str( int *a, int len ){
    char *s = new char [len + 1];

    int i(0);
    while ( i != len )
        s[i++] = a[len - 1 - i] + '0';

    s[len] = '\0';

    return s;
}

int check( int *a, int len ){
    for ( int i(0); i != len; ++i )
        if ( a[i] > 9 ){
            a[i + 1] += a[i]/10;
            a[i] = a[i]%10;
        }

    //去零,确定长度
    while ( 0 == a[len - 1] && len > 1)
        --len;

    return len;
}
*/




 

你可能感兴趣的:(数据结构与算法)