码迷,mamicode.com
首页 > 其他好文 > 详细

BigInteger

时间:2014-12-01 12:50:27      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:io   ar   os   sp   for   on   art   bs   amp   

#include <iostream>
#include <cstring>
#include <vector>
#include<stdio.h>
using namespace std;
struct BigInteger {
    static const int BASE = 100000000;
    static const int WIDTH = 8;
    vector<int> s;
    BigInteger operator = (const string& str) {
        s.clear();
        int x,len = (str.length()-1)/WIDTH +1;
        for(int i =0; i<len; i++) {
            int end = str.length() - i*WIDTH;
            int start = max(0,end-WIDTH);
            sscanf(str.substr(start,end-start).c_str(),"%d",&x);
            s.push_back(x);
        }
        return *this;
    }
    BigInteger operator + (const BigInteger& b){
        BigInteger c;
        c.s.clear();
        for(int i=0,g=0;;i++){
            if(g==0&& i>=s.size()&&i>=b.s.size()) break;
            int x = g;
            if(i< s.size())x+=s[i];
            if(i<b.s.size())x+=b.s[i];
            c.s.push_back(x%BASE);
            g = x/BASE;
        }
        return c;
    }
};

ostream& operator << (ostream &out,const BigInteger& x) {
    out<<x.s.back();
    for(int i=x.s.size()-2; i>=0; i--) {
        char buf[20];
        sprintf(buf,"%08d",x.s[i]);
        for(int j=0; j<strlen(buf); j++)
            out<<buf[j];
    }
    return out;
}
istream& operator >> (istream &in,BigInteger& x){
    string s;
    if(!(in>>s))return in;
    x = s;
    return in;
}

int main() {
    BigInteger a ;
    BigInteger b;
    BigInteger c;
    cin>>a>>b;
    c = a+b;
    cout<<c<<endl;
    return 0;
}

BigInteger

标签:io   ar   os   sp   for   on   art   bs   amp   

原文地址:http://www.cnblogs.com/daipeiwu/p/4134694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!