题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002
题目描述:大数相加问题
解题思路:原来都是借助数组实现的,最近开始运用STL,这次借助链表实现了下。
- #include<iostream>
- #include<string>
- #include<list>
- using namespace std;
- class BigInt
- {
- friend istream& operator>>(istream&, BigInt&);
- friend ostream& operator<<(ostream&, BigInt&);
- friend BigInt& operator+(BigInt&, BigInt&);
- private:
- list<int> intLst;
- };
- BigInt& operator+(BigInt& a, BigInt& b)
- {
- int carry=0;//进位标志
- list<int>::reverse_iterator rIterA=a.intLst.rbegin();
- list<int>::reverse_iterator rIterB=b.intLst.rbegin();
- BigInt* c=new BigInt();
- while(rIterA!=a.intLst.rend() && rIterB!=b.intLst.rend())
- {
- c->intLst.push_front((*rIterA+*rIterB+carry)%10);
- if((*rIterA+*rIterB+carry)>=10)
- carry=1;
- else
- carry=0;
- rIterA++, rIterB++;
- }
- while(rIterA!=a.intLst.rend())
- {
- c->intLst.push_front((*rIterA + carry)%10);
- if((*rIterA + carry)>=10)
- carry=1;
- else
- carry=0;
- rIterA++;
- }
- while(rIterB!=b.intLst.rend())
- {
- c->intLst.push_front((*rIterB +carry)%10);
- if((*rIterB + carry)>=10)
- carry=1;
- else
- carry=0;
- rIterB++;
- }
- if(carry == 1)
- c->intLst.push_front(1);
- return *c;
- }
- istream& operator>>(istream& in, BigInt& bint)
- {
- string str;
- in>>str;
- for(string::iterator iter=str.begin(); iter!=str.end(); iter++)
- bint.intLst.push_back(*iter-'0');
- return in;
- }
- ostream& operator<<(ostream& out, BigInt& bint)
- {
- for(list<int>::iterator iter=bint.intLst.begin();iter!=bint.intLst.end();iter++)
- out<<*iter;
- return out;
- }
- int main()
- {
- int t,cnt;
- cin>>t;
- cnt=0;
- while(t--)
- {
- cnt++;
- BigInt* a=new BigInt();
- BigInt* b=new BigInt();
- cin>>*a>>*b;
- BigInt c=*a+*b;
- cout<<"Case "<<cnt<<":/n";
- cout<<*a<<" + "<<*b<<" = "<<c<<endl;
- if(t != 0)
- cout<<endl;
- }
- return 0;
- }