大整数,四则运算

// 四则运算,负数情况未处理 
#include <cstdio>
#include <cstring>
#include <algorithm> 
using namespace std;

struct bignum
{
    int d[1000];
    int len;
    bignum()
    {
        memset(d, 0, sizeof(d));
        len = 0;
    }
};

bignum change(char str[])
{
    bignum a;
    a.len = strlen(str);
    for(int i = 0; i < a.len; i++)
        a.d[i] = str[a.len - 1 - i] - '0';
    return  a;
}

int compare(bignum a, bignum b)
{
    if(a.len > b.len) return 1;
    else if(a.len < b.len) return -1;
    else
    {
        for(int i = a.len-1; i >= 0; i--)
        {
            if(a.d[i] > b.d[i])
                return 1;
            else if(a.d[i] < b.d[i])
                return -1;
        }
        return 0;
    }
}

bignum add(bignum a, bignum b)
{
    bignum c;
    int carry = 0;
    for(int i = 0; i < a.len || i < b.len; i++)
    {
        int temp = a.d[i] + b.d[i] + carry;
        c.d[c.len++] = temp % 10;
        carry = temp / 10;
    }
    if(carry != 0)
        c.d[c.len++] = carry;
    return c;
}

bignum sub(bignum a, bignum b)
{
    if(compare(a, b) < 0)
    {
        swap(a, b);
        printf("-");
    }
    bignum c;
    for(int i = 0; i < a.len || i < b.len; i++)
    {
        if(a.d[i] < b.d[i])
        {
            a.d[i+1]--;
            a.d[i] += 10;
        }
        c.d[c.len++] = a.d[i] - b.d[i];
    }
    while(c.len - 1 >= 1 && c.d[c.len-1] == 0)
        c.len--;
    return c;
}

bignum multi(bignum a, int b)
{
    bignum c;
    int carry = 0;
    for(int i = 0; i < a.len; i++)
    {
        int temp = a.d[i] * b + carry;
        c.d[c.len++] = temp % 10;
        carry = temp / 10;
    } 
    while(carry != 0)
    {
        c.d[c.len++] = carry % 10;
        carry /= 10;
    }
    return c;
}

bignum divide(bignum a, int b, int &r)
{
    bignum c;
    c.len = a.len;
    for(int i = a.len-1; i >= 0; i--)
    {
        r = r * 10 + a.d[i];
        if(r < b) c.d[i] = 0;
        else
        {
            c.d[i] = r / b;
            r = r % b;
        } 
    }
    while(c.len - 1 >= 1 && c.d[c.len-1] == 0)
        c.len--;
    return c;
} 

void print(bignum a)
{
    for(int i = a.len-1; i >= 0; i--)
        printf("%d",a.d[i]);
    printf("\n");
}

int main()
{
    char str1[1000], str2[1000];
    scanf("%s%s",str1, str2);
    bignum a = change(str1);
    bignum b = change(str2);
    print(add(a, b));
    print(sub(a, b));
    int k = 10;
    printf("bignum a * 10 = ");
    print(multi(a, k));
    int r = 0;
    printf("bignum a / 10 = ");
    print(divide(a, k, r));

    return 0;
}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页