大数加,减,乘。纯模拟模板

大整数加法:

char tmp[210];                 /// add

void bigadd(char *s,char *t){
    int lens = strlen(s),lent = strlen(t);
    int xx[210] = {0};
    int p = 0;
    while(lens > 0 && lent > 0) xx[p ++] = s[-- lens] - '0' + t[-- lent] - '0';
    while(lens > 0) xx[p ++] = s[-- lens] - '0';
    while(lent > 0) xx[p ++] = t[-- lent] - '0';

    for(int i = 0;i < p;i ++)
        if(xx[i] >= 10){
            xx[i] -= 10;
            xx[i + 1] ++;
        }

    int pt = 0;
    if(xx[p] != 0) tmp[pt ++] = xx[p] + '0';
    while(p > 0) tmp[pt ++] = xx[-- p] + '0';
    tmp[pt] = '\0';
}

大整数减:

char tmp[210];                  /// jian

void bigjian(char *a, char *b) {      // a - b
    int i = strlen(a) - 1, j = strlen(b) - 1;
    int x = 0, c[205] = {0}, flag = 1, d[205] = {0}, f[205] = {0};
    for(int l = 0; l <= i; l++)
        c[l] = a[l] - '0';
    for(int l = 0; l <= j; l++)
        d[l] = b[l] - '0';
    while(j != -1) {
        if(c[i] < d[j]) {
            c[i] += 10;
            c[i - 1] -= 1;
        }
        f[x++] = c[i] - d[j];
        i--;
        j--;
    }
    while(i >= 0) {
        if(c[i] < 0) {
            c[i] += 10;
            c[i - 1] -= 1;
        }
        f[x++] = c[i];
        i--;
    }
    int p = 0;
    if(f[x - 1] == 0)
        flag = 0;
    for(int y = x - 1; y >= 0; y--) {
        if(f[y] != 0)
            flag = 1;
        if(flag == 1)
            tmp[p ++] = f[y] + '0';
    }
    if(flag == 0)
        tmp[p ++] = '0';
    tmp[p] = '\0';
}

大整数乘:// O(lena * lenb)

char tmp[210];                 /// cheng

void bigx(char *a, char *b) {
    int x, k, lena, lenb, lenb1, c[210] = {0};
    lena = strlen(a) - 1;
    lenb = strlen(b);
    lenb1 = lenb;
    while(lenb--) {
        x = lenb1 - lenb - 1;
        for(int i = lena; i >= 0; i--) {
            k = (a[i] - '0') * (b[lenb] - '0');
            c[x] += k;
            if(c[x] >= 10) {
                c[x + 1] += c[x] / 10;
                c[x] %= 10;
            }
            x++;
        }
    }
    int p = 0;
    if(c[x] != 0)
        tmp[p ++] = c[x] + '0';
    for(int i = x - 1; i >= 0; i--)
        tmp[p ++] = c[i] + '0';
    tmp[p] = '\0';
}

猜你喜欢

转载自blog.csdn.net/no_O_ac/article/details/82818640
今日推荐