list实现大整数加法

时间:2023-01-25 19:43:52
#include<iostream>
#include<list>
#include<string>
using namespace std;


list<int> BigAddList(list<int> La,list<int> Lb )
{
    list<int> Lc;
    list<int> ::iterator it1,it2;
    it1=La.begin();
    it2=Lb.begin();
    
    int carry=0;
    while(it1!=La.end()||it2!=Lb.end())
    {
        int c=carry;
        if(it1!=La.end())
        {
            c=c+(*it1);
            it1++;
        }
        if(it2!=Lb.end())
        {
            c=c+(*it2);
            it2++;
        }
        carry=c/10;
        Lc.push_back(c%10); 
     } 
     if(carry>0) Lc.push_back(carry);
     return Lc;
}



int main()
{
    int i,T;
    cin>>T;
    for(int j=0;j<T;j++)
    {
        string s,t;
        cin>>s>>t;
        list<int>La,Lb,Lc;
        
        for(i=0;i<s.size();i++)
        {
            La.push_front(s[i]-'0');
            
         } 
         for(i=0;i<t.size();i++)
         Lb.push_front(t[i]-'0');
         
         Lc=BigAddList(La,Lb);
         Lc.reverse();
         
         for(list<int>::iterator it=Lc.begin();it!=Lc.end();it++)
         {
             cout<<*it;
             
         
         }
         cout<<endl;
    }
}