高精度计算 大数乘法

#include <iostream>
#include <cstring>

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;
}
*/




 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值