3605 - 后缀表达式求值
时间限制 : 1 秒
内存限制 : 128 MB
将输入的后缀表达式求值后输出
题目输入
输入一行表示后缀表达式,注意每个数或符号之间有一空格隔开,最后输入@表示输入结束。
题目输出
输出一个数,表示该表达式的值
输入/输出样例
输入格式
14 3 20 5 / *8 - + @
输出格式
18
C语言解答
#include <stdio.h> main(){ int n,t=-1,i=0,a[255];char s[255]; gets(s); while(s[i]!='@'){n=0; while(s[i]>='0'&&s[i]<='9'){ n=n*10+s[i]-'0';i++; } if(n!=0){++t;a[t]=n;} if(s[i]=='+'){a[t-1]=a[t-1]+a[t];t--;} if(s[i]=='-'){a[t-1]=a[t-1]-a[t];t--;} if(s[i]=='*'){a[t-1]=a[t-1]*a[t];t--;} if(s[i]=='/'){a[t-1]=a[t-1]/a[t];t--;} i++; } printf("%d ",a[0]); }
C++解答
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cstdlib> #include<cctype> #include<stack> #define num x using namespace std; stack<int>num,sym; int a[255]; char s[300]; int main(){ /*freopen("strs.in","r",stdin); freopen("strs.out","w",stdout);//*/ char ch; ch=getchar(); while(ch!='@'){ int k=0; while(isalnum(ch)){ k=k*10+ch-48; ch=getchar(); } //cout<<k<<' '; if(!(ch!='0'&&k==0))num.push(k); while(ch==' ')ch=getchar(); //cout<<ch; if(!isalnum(ch)){ if(ch=='+'){ int k1=x.top(); x.pop(); int k2=x.top(); x.pop(); x.push(k1+k2); } else if(ch=='-'){ int k1=x.top(); x.pop(); int k2=x.top(); x.pop(); //cout<<k1<<' '<<k2; x.push(k2-k1); } else if(ch=='*'){ int k1=x.top(); x.pop(); int k2=x.top(); x.pop(); x.push(k2*k1); } else if(ch=='/'){ int k1=x.top(); x.pop(); int k2=x.top(); x.pop(); x.push(k2/k1); } ch=getchar(); while(ch==' ')ch=getchar(); } } int k=x.top(); cout<<k; //while(1); return 0; }