A + B Problem II && Hat's Fibonacci

#include <iostream>
#include <string>
using namespace std;
string add(const string &a,const string &b)
{
    int dig = 0;//进位符
    string a1,b1;
    if(a.size()>b.size())
    {
        a1 = a;
        b1 = b;
    }else
    {    
        a1 = b;
        b1 = a;
    }
    int clen = a1.size() - b1.size();
    for (int i = 0; i < clen ; i++)
    {
        string zero(1,'0');
        b1.insert(0,zero);
    }
    for (int i = a1.size() - 1; i >= 0 ; i--)
    {
        int t = (int)a1[i] + (int)b1[i] - '0' - '0';
        a1[i] = char(( t + dig)%10 + '0');
        dig = ( t + dig) /10;
    }
    if(dig!=0)
    {
        string d(1,char(dig+48));
        a1.insert(0,d);
    }
    return a1;
}


int main()
{

    int T;
    string A,B;
    cin>>T;
    for (int i = 0; i < T; i++)
    {
        
        cin>>A;
        cin>>B;
        cout<<"Case "<<i+1<<":"<<endl;
        cout<<A<<" + "<<B<<" = "<<add(A,B)<<endl;
        if(i!=T-1)
        cout<<endl;

    }
    return 0;
}
#include <iostream>
#include <string>
using namespace std;
string add(const string &a,const string &b)
{
    int dig = 0;
    string a1,b1;
    if(a.size()>b.size())
    {
        a1 = a;
        b1 = b;
    }
    else
    {
        a1 = b;
        b1 = a;
    }
    int clen = a1.size() - b1.size();
    for (int i = 0; i < clen ; i++)
    {
        string zero(1,'0');
        b1.insert(0,zero);
    }
    for (int i = a1.size() - 1; i >= 0 ; i--)
    {
        int t = (int)a1[i] + (int)b1[i] - '0' - '0';
        a1[i] = char(( t + dig)%10 + '0');
        dig = ( t + dig) /10;
    }
    if(dig!=0)
    {
        string d(1,char(dig+48));
        a1.insert(0,d);
    }
    return a1;
}


int main()
{
    string record[10000];

    record[1]=record[2]=record[3]=record[4]="1";
    for(int i=5; i<7039; i++)
    {
        record[i] = add(add(record[i-1],record[i-2]),add(record[i-3],record[i-4]));
    }
    int T;
    while(cin>>T)
        cout<<record[T]<<endl;
}

 

posted @ 2013-09-19 16:02  Destino74  阅读(98)  评论(0编辑  收藏  举报