[sicily online]1159. Sum(字符串加法)

#include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
#include<bitset>
using namespace std;
int main()
{
	int n;
	while(cin>>n&&n>0)
	{
		vector<string> data(n);
		string sum("0");
		for(int i=0;i<n;i++)
		{
			cin>>data[i];
			reverse(data[i].begin(),data[i].end());//字符串反转
			int flag=0;
			int j=0;
			for(j=0;j<data[i].size()&&j<sum.size();j++)
			{
				int result=0;
				result=flag+(data[i][j]-'0')+(sum[j]-'0');
				if(result>=10)
				{
					flag=1;
					result=result-10;
				}
				else flag=0;
				sum[j]=result+'0';
			}//end for j
			if(j>=sum.size())
			{
				sum=sum+data[i].substr(j,data[i].size()-j);
			}
			if(flag==1)
			{
				while(1)
				{
					if(j>=sum.size())
					{
						sum=sum+"1";
						break;
					}
					else
					{
						sum[j]++;
						if(sum[j]>'9')
						{
							sum[j]='0';
							j++;
						}
						else break;
					}
				}
			}
		}
		reverse(sum.begin(),sum.end());
		cout<<sum<<endl;
	}
}

你可能感兴趣的:([sicily online]1159. Sum(字符串加法))