题目
答案
#include<stack>
#include<stdio.h>
using namespace std;
int main()
{
stack<char> s;
char str[100];
int flag=0;
scanf("%s",str);
for(int i=0;str[i];i++)
{
if((str[i]=='-'||str[i]=='+')&&i==0)
printf("%c",str[i]);
else if(str[i]=='.') printf(".");
else if(str[i]>='0'&&str[i]<='9')
{
if(!(str[i-1]>='0'&&str[i-1]<='9')&&str[i-1]!='.')
{
if(flag==0)
{
printf("%c",str[i]);flag=1;
}
else printf(" %c",str[i]);
}
else if((str[i+1]>='0'&&str[i+1]<='9')||str[i+1]=='.'||str[i-1]=='.'||(str[i-1]>='0'&&str[i-1]<='9')) printf("%c",str[i]);
else if(flag==0)
{
printf("%c",str[i]);flag=1;
}
else printf(" %c",str[i]);
}
else
{
if(s.empty()||str[i]=='(') s.push(str[i]);
else if(str[i]==')')
{
while(s.top()!='(')
{
printf(" %c",s.top());
s.pop();
}
s.pop();
}
else if((str[i]=='+'||str[i]=='-')&&(str[i-1]=='(')&&(str[i+1]>='0'&&str[i+1]<='9'))
{
if(flag==0)
{
printf("%c",str[i+1]);flag=1;
}
else printf(" %c",str[i+1]);
i++;
}
else if((str[i]=='+'||str[i]=='-')&&(s.top()=='+'||s.top()=='-'||s.top()=='*'||s.top()=='/'))
{
printf(" %c",s.top());
s.pop();
i--;
}
else if((str[i]=='+'||str[i]=='-')&&(s.top()=='(')) s.push(str[i]);
else if((str[i]=='*'||str[i]=='/')&&(s.top()=='*'||s.top()=='/'))
{
printf(" %c",s.top());
s.pop();
i--;
}
else if((str[i]=='*'||str[i]=='/')&&(s.top()=='+'||s.top()=='-'||s.top()=='(')) s.push(str[i]);
}
}
while(!s.empty())
{
printf(" %c",s.top());
s.pop();
}
printf("\n");
}
详细测试点
序号 | 输入 | 输出 | 说明 |
---|---|---|---|
0 | 2+3*(7-4)+8/4 | 2 3 7 4 - * + 8 4 / + | 正常测试6种运算符 |
1 | ((2+3)*4-(8+2))/5 | 2 3 + 4 * 8 2 + - 5 / | 嵌套括号 |
2 | 1314+25.5*12 | 1314 25.5 12 * + | 运算数超过1位整数且有非整数出现 |
3 | -2*(+3) | -2 3 * | 运算数前有正负号 |
4 | 123 | 123 | 只有一个数字 |
(尤其注意序号为2和3的两个测试点)