HDOJ1002

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002

题目描述:大数相加问题

解题思路:原来都是借助数组实现的,最近开始运用STL,这次借助链表实现了下。

  1. #include<iostream>
  2. #include<string>
  3. #include<list>
  4. using namespace std;
  5. class BigInt
  6. {
  7.     friend istream& operator>>(istream&, BigInt&);
  8.     friend ostream& operator<<(ostream&, BigInt&);
  9.     friend BigInt& operator+(BigInt&, BigInt&);
  10. private:
  11.     list<int> intLst;
  12. };
  13. BigInt& operator+(BigInt& a, BigInt& b)
  14. {
  15.     int carry=0;//进位标志
  16.     list<int>::reverse_iterator rIterA=a.intLst.rbegin();
  17.     list<int>::reverse_iterator rIterB=b.intLst.rbegin();
  18.     
  19.     BigInt* c=new BigInt();
  20.     while(rIterA!=a.intLst.rend() && rIterB!=b.intLst.rend())
  21.     {
  22.         c->intLst.push_front((*rIterA+*rIterB+carry)%10);
  23.         if((*rIterA+*rIterB+carry)>=10)
  24.             carry=1;
  25.         else
  26.             carry=0;
  27.         rIterA++, rIterB++;
  28.     }
  29.     while(rIterA!=a.intLst.rend())
  30.     {
  31.         c->intLst.push_front((*rIterA + carry)%10);
  32.         if((*rIterA + carry)>=10)
  33.             carry=1;
  34.         else
  35.             carry=0;
  36.         rIterA++;
  37.     }
  38.     while(rIterB!=b.intLst.rend())
  39.     {
  40.         c->intLst.push_front((*rIterB +carry)%10);
  41.         if((*rIterB + carry)>=10)
  42.             carry=1;
  43.         else
  44.             carry=0;
  45.         rIterB++;
  46.     }
  47.     if(carry == 1)
  48.         c->intLst.push_front(1);
  49.     return *c;
  50. }
  51. istream& operator>>(istream& in, BigInt& bint)
  52. {
  53.     string str;
  54.     in>>str;
  55.     for(string::iterator iter=str.begin(); iter!=str.end(); iter++)
  56.         bint.intLst.push_back(*iter-'0');
  57.     return in;
  58. }
  59. ostream& operator<<(ostream& out, BigInt& bint)
  60. {
  61.     for(list<int>::iterator iter=bint.intLst.begin();iter!=bint.intLst.end();iter++)
  62.         out<<*iter;
  63.     return out;
  64. }
  65. int main()
  66. {
  67.     int t,cnt;    
  68.     cin>>t;
  69.     cnt=0;
  70.     while(t--)
  71.     {
  72.         cnt++;
  73.         BigInt* a=new BigInt();
  74.         BigInt* b=new BigInt();
  75.         
  76.         cin>>*a>>*b;
  77.         BigInt c=*a+*b;
  78.         cout<<"Case "<<cnt<<":/n";
  79.         cout<<*a<<" + "<<*b<<" = "<<c<<endl;
  80.         if(t != 0)
  81.             cout<<endl;
  82.     }
  83.     return 0;
  84. }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值