华为机试 - 一串正整数相加

输入一串正整数字符,各正整数之间用空格分开,只有数字字符和空格有效,其他字符均为无效;
   输入正整数个数不超过32个(即:正整数个数<=32)。
   若出现无效字符,输出ERROR;若输入正整数个数超过32个,输出ERROR。
   若有效,则求出总和;
   
   例子:
   输入:12 a34   输出:ERROR

   输入:12 34    输出:46

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void add(string &result, string &temp)
{
	if (result.size()<temp.size())
		swap(result,temp);
	int carry=0;
	size_t i=0;
	for (;i<temp.size();i++)
	{
		int adder=carry+result[i]-'0'+temp[i]-'0';
		result[i]=adder%10+'0';
		carry=adder/10;
	}
	if (carry!=0)
	{
		for (;i<result.size();i++)
		{
			result[i]=(carry+result[i]-'0')%10+'0';
			carry=(carry+result[i]-'0')/10;
		}
	}
	if (carry)
	{
		result+='1';
	}
}

int main()
{
	string str;
	getline(cin,str);
	string result,temp;
	int numInt=0;
	bool space=true;
	for(size_t i=0;i<str.size();i++)
	{
		if((str[i]>'9'||str[i]<'0')&&str[i]!=' ') 
		{
			cout<<"ERROR"<<endl;
			system("pause");
			return -1;
		}
		if (str[i]==' ')
		{
			space=true;
			reverse(temp.begin(),temp.end());
			add(result,temp);
			temp.clear();
		}
		if(space&&str[i]<'9'&&str[i]>'0')
		{
			space=false;
			numInt++;
			if(numInt>32)
			{
				cout<<"ERROR"<<endl;
				system("pause");
				return -2;
			}
		}
		if(!space)
		{
			temp+=str[i];
		}

	}
	if(!temp.empty())
	{
		reverse(temp.begin(),temp.end());
		add(result,temp);
	}
	reverse(result.begin(),result.end());
	cout<<result<<endl;
	system("pause");
	return 0;
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值