P1601一道高精度的题

#include <iostream> 
#include <cstring>    // use strlen
#include <string> 
using namespace std; 
const int Max = 5e2+10; 

class st {
private: 
    char num[Max]; 
    int n; 
public:
    st();
    void Reset(char * a, int len);
    st operator+(const st & b); 
    friend ostream & operator<<(ostream & os, st ans); 
};

st::st() { 
    n = 0;
    for (int i = 0; i < Max; ++i) 
        num[i] = '\0';
}

void st::Reset(char * a, int len) {
    for (int i = 0; i < len; ++i) 
        num[len-i-1] = a[i]; 
    n = len;     
}

st st::operator+(const st & b) {
    st c;
    int i;
    int getin = 0;
    for (i = 0; num[i] || b.num[i]; ++i) {
        int a1 = 0, b1 = 0; 
        if (i < strlen(num)) a1 = num[i] - '0';
        if (i < strlen(b.num)) b1 = b.num[i] - '0';
        getin += a1 + b1;
        c.num[i] = getin % 10 + '0';
        getin /= 10;
    }
    if (getin) 
        c.num[i++] = getin + '0'; 
    c.n = i; 
    return c;     
}

ostream & operator<<(ostream & os, st ans) {
    for (int i = ans.n-1; i >= 0; --i) 
        os << ans.num[i]; 
    return os;     
}

int main() { 
     char a[Max], b[Max];
    st A, B; 
    cin >> a >> b; 
    A.Reset(a, strlen(a)); 
    B.Reset(b, strlen(b));  
    cout << A+B << endl;  
    return 0;
}

 https://www.luogu.org/problemnew/show/P1601

posted @ 2019-04-15 21:13  yifei_Wa  阅读(203)  评论(1编辑  收藏  举报