游客 Signup | Login
中文 | En

3605 - 后缀表达式求值

将输入的后缀表达式求值后输出

Input

输入一行表示后缀表达式,注意每个数或符号之间有一空格隔开,最后输入@表示输入结束。

Output

输出一个数,表示该表达式的值

Examples

Input

14  3 20 5 / *8 - + @

Output

18

Solution 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]);	
} 

Solution 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;
}
Time Limit 1 second
Memory Limit 128 MB
Discuss Stats
上一题 下一题