Friday, November 2, 2012

Big Integer Addition in C++


#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string fill(string a, int n){
    while(a.size()<n) a='0'+a;
    return a;
}

string add(string a, string b){

    int m=max(a.size(),b.size());

    a=fill(a,m);
    b=fill(b,m);

    int car=0;
    string res;

    for(int i=m-1;i>=0;i--){
        int z=((a[i]+b[i]-2*'0'+car)%10);
        res+=(z+'0');
        car=((a[i]+b[i]-2*'0'+car)/10);
    }

    if(car>0) res+='1';

    reverse(res.begin(), res.end());

    return res;
}

int main()
{
    string as,bs;
    while(cin>>as>>bs){
        cout<<add(as,bs)<<endl;
    }
    return 0;
}


No comments:

Post a Comment