大數加法

一͛世͛珍͛藏͛發表於2019-05-13
#define MAXN 1000000000

class BigNum {
    unsigned a[10];
    int len;
    void _add(int i, unsigned d) {
        while(len <= i) a[len++] = 0;
        a[i] += d;
    }
    void add(int i, unsigned d) {
        _add(i, d);
        while(a[i] >= MAXN) {
            a[i++] -= MAXN;
            _add(i, 1);
        }
    }
public:
    BigNum(unsigned d = 0) {
        len = 0;
        while(d >= MAXN) {
            a[len++] = d % MAXN;
            d /= MAXN;
        }
        a[len++] = d;
    }
    void operator += (BigNum &n) {
        for(int i=0; i<n.len; i++) add(i, n.a[i]);
    }
    void print() {
        printf("%u", a[len-1]);
        for(int i=len-2; i>=0; i--) printf("%09u", a[i]);
        printf("
");
    }
};

相關文章