2017.11.6

题目描述

请设计一个算法能够完成两个用字符串存储的整数进行相加操作,对非法的输入则返回error

输入描述:

输入为一行,包含两个字符串,字符串的长度在[1,100]。

输出描述:

输出为一行。合法情况输出相加结果,非法情况输出error
示例1

输入

123 123
abd 123

输出

246
Error



#include<iostream>
#include<string>
#include<stack> //出入栈头文件
using namespace std;
int main()
{
string s1,s2;
cin>>s1>>s2;
int len1=s1.length();
int len2=s2.length();
int len=len1<len2?len2:len1;
int t=0,b;
stack<int > tmp; //入栈
for(int i=len-1;i>=0;i--)
{
if(('0'<=s1[i]&&s1[i]<='9')&&('0'<=s2[i]&&s2[i]<='9'))
{
int y=s1[i]-'0'+s2[i]-'0';
b=y%10+t;
t=y/10;

tmp.push(b);
}
else
{
cout<<"error";

return 0;
}
}
if(t!=0)
cout<<t;
while(!tmp.empty())//出栈
{
b=tmp.top();
cout<<b;
tmp.pop();
}
}

原文地址:https://www.cnblogs.com/panlangen/p/7795788.html