手记

大整数相加

?

#include "stdafx.h"#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std;int _tmain(int argc, _TCHAR* argv[]){    string sa,sb,sc;    vector<int>v;    int i,a,b,sum,flag;    while(cin>>sa>>sb)    {        flag=0;//进位初始化为0        v.clear();//清空结果向量        sum=0;        reverse(sa.begin(),sa.end());//逆序相加        reverse(sb.begin(),sb.end());//逆序相加        //cout<<sa<<endl;        //cout<<sb<<endl;        if(sa.size()<sb.size())        {           sc=sa;           sa=sb;           sb=sc;        }        for(i=0;i<sa.size();i++)        {             if(i>=sb.size())  sb[i]='0';                         sum=sa[i]-'0'+sb[i]-'0'+flag;        if(sum>9)        {            flag=sum/10;//产生进位            sum=sum%10;//保留位        }        else            flag=0;          v.push_back(sum);        }        if(flag==1)  v.push_back(1);        for(i=v.size()-1;i>=0;i--)//最后再逆序输出        {           cout<<v[i];                  }        cout<<endl;      }    return 0;}
0人推荐
随时随地看视频
慕课网APP