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