洛谷P1449 【后缀表达式】
这题其实思路很简单,就是每次碰到‘.’,将其前面的数字存入栈中。(注意:点号前的数字可能不止一位)。然后只要碰到操作运算符,就把存入栈中的数字拿出来运算好后,再放回去。最后栈就只剩一个最后的运算结果。
#include<bits/stdc++.h>
using namespace std;
char a[8000];
int main()
{
gets(a);//读入字符串
stack<int> s;//建立int型的栈
for(int i=0;i<strlen(a)-1;i++)
{
if(a[i]=='.')//如果遇到‘.’,把‘.’之前的数记录下来
{
int sum=0,k=0;//k是位数,sum存被操作的数字
for(int j=i-1;j>=0;j--)//从当前位置往前查找
{
if(a[j]=='.')//碰到前一个‘.’退出
break;
else if(a[j]<'0'||a[j]>'9')//如果碰到运算符号也退出
break;
if(k==0)//如果只有一位数字,直接加到sum里
{
sum=a[j]-'0';
k++;
}
else//如果不是一位数,模拟加法的进位
{
int temp=1;
for(int p=1;p<=k;p++)
temp*=10;
sum=sum+(a[j]-'0')*temp;
k++;
}
}
s.push(sum);//将被操作数字压入栈
}
else if(a[i]=='+')//出现运算符就弹出两个数,然后进行运算
{
int x=s.top();
s.pop();
int y=s.top();
s.pop();
s.push(x+y);//将运算结果再压回去
}
else if(a[i]=='-')//同上
{
int x=s.top();
s.pop();
int y=s.top();
s.pop();
s.push(y-x);
}
else if(a[i]=='*')//同上
{
int x=s.top();
s.pop();
int y=s.top();
s.pop();
s.push(x*y);
}
else if(a[i]=='/')//同上
{
int x=s.top();
s.pop();
int y=s.top();
s.pop();
s.push(y/x);
}
}
printf("%d",s.top());//由于不断的弹两个,压回去一个,最终剩下的就是最终运算结果。
return 0;
}