【题解】洛谷 P1449 后缀表达式

[TOC]

题目

P1449 后缀表达式

思路

栈。题目说的不是很清楚,没说包含什么操作。除法用整数除法就行。
先string读入字符串,然后从前往后看如果是个数字就入栈,如果是运算符就从栈里弹出两个数计算再入栈。
###\(Code\)

#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<stack>
#include<algorithm>
std::string sss;
std::stack<int> s1;

inline void read(int &T) {
	int x=0;bool f=0;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=!f;c=getchar();}
	while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
	T=f?-x:x;
}

int main() {
	std::cin>>sss;
	int len=sss.length();
	int sum=0;
	for(int i=0;i<len-1;++i) {
		if(sss[i]>='0'&&sss[i]<='9') {
			sum=sum*10+sss[i]-'0';
		}else {
			if(sss[i]=='.') {
				s1.push(sum);
				sum=0;
			}
			else {
				int x1=s1.top();
				s1.pop();
				int x2=s1.top();
				s1.pop();
				if(sss[i]=='+') s1.push(x1+x2);
				if(sss[i]=='-') s1.push(x2-x1);
				if(sss[i]=='*') s1.push(x2*x1);
				if(sss[i]=='/') s1.push(x2/x1);
			}
		}
	}
	std::cout<<s1.top();
	return 0;
}
posted @ 2019-10-07 14:42  yu__xuan  阅读(347)  评论(0编辑  收藏  举报