计算A+B
题目链接
在一行中给出一个字符串,请判断是否满足A + B格式,如果满足,输出计算结果,否则输出"skipped"。
此处A,B均为大于等于0的整数,不保证数据没有前导零。
输入描述:
第一行输入一个n, 1 \le n \le 1000n,1≤n≤1000,代表测试数据的组数。
接下来n行,每行输入一个长度不超过10000的字符串。
输出描述:
对于每组输入,输出结果
输入
4
2+2
1+2
+12
0+0
输出
4
3
skipped
0
算法分析
高精度加法模拟,处理前导零
代码实现
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
int cnt=0,pos;
int len=s.length();
for(int i=0;i<s.length();i++)
{
if(s[i]=='+')
{
cnt++,pos=i;
}
}
if(cnt!=1)
cout<<"skipped"<<endl;
else if(s[0]=='+'||s[len-1]=='+')
cout<<"skipped"<<endl;
else
{
int form=0,last=pos+1,qian=pos-1,hou=len-1;
while(s[form]=='0') form++;
while(s[last]=='0') last++;
if(form>qian&&last>hou)
{
cout<<'0'<<endl;
}
else
{
string ans;
int a=0,b=0,cnt=0,t=0;
while(form<=qian||last<=hou)
{
a=b=0;
if(form<=qian) a=s[qian]-'0';
if(last<=hou) b=s[hou]-'0';
ans[cnt++]=(a+b+t)%10+'0';
t=(a+b+t>9);
qian--,hou--;
}
if(t)
ans[cnt++]=t+'0';
for(int i=cnt-1;i>=0;i--)
cout<<ans[i];
cout<<endl;
}
}
}
}