C++大数相加

#include <iostream>
#include <string>
#include <stack>

using namespace std;

string Add(string Str1, string Str2)
{
 // 操作数1
 stack<int>S1;
 // 操作数2
 stack<int>S2;
 // 结果
 stack<int>S3;

 int i, r, last = 0;
 for(i=0; i<Str1.size(); i++)
  S1.push(Str1[i] - '0');
 for(i=0; i<Str2.size(); i++)
  S2.push(Str2[i] - '0');

 while(!S1.empty() && !S2.empty())
 {
  r = S1.top() + S2.top() +last;
  S3.push(r%10);
  last = r/10;
  S1.pop();
  S2.pop();
 }

 if(!S1.empty())
 {
  while(!S1.empty())
  {
   r = S1.top() + last;
   S3.push(r%10);
   last = r/10;
   S1.pop();
  }
 }
 else if(!S2.empty())
 {
  while(!S2.empty())
  {
   r = S2.top() + last;
   S3.push(r%10);
   last = r/10;
   S2.pop();
  }
 }

 if(last != 0)
  S3.push(last);
 string result;
 while(!S3.empty())
 {
  result += S3.top() + '0';
  S3.pop();
 }

 return result;
}

int main(int argc, char* argv[])
{
 int i, N;
 cin>>N;
 string a, b;
 string* answer = new string[N];
 for(i=0; i<N; i++)
 {
  cin>>a>>b;
  answer[i] = Add(a, b);
 }

 for(i=0; i<N; i++)
 {
  cout<<answer[i]<<endl;
 }
 delete[] answer;
 return 0;
}

posted on 2008-12-18 19:22  小橋流水  阅读(648)  评论(0编辑  收藏  举报

导航