Emacs計算器

牛客網題目鏈接

後綴表達式計算

遇到數值直接放入棧中,遇到操作符將棧頂的兩個操作數取出來,然後進行加減乘除操作。注意做除法和減法時,後取出的一個數是被除數和被減數。注意數值中可能有負數。

#include <cstdio>
#include <iostream>
#include <string>
#include <unordered_map>
#include <stack>
#include <algorithm>
using namespace std;
int main(){
	int n;
	string str;
	
	while(cin>>n){
		stack<int> st;
		for(int i = 0; i < n; i++){
			
			cin>>str;
		
			if(str.size() == 1 && (str[0] == '+'|| str[0] == '-'|| str[0] == '*'|| str[0] == '/')){
				
				int p = st.top();
				st.pop();
				int q = st.top();
				st.pop();
				switch(str[0]){
					case '+': st.push(p+q); break;
					case '-': st.push(q-p); break;
					case '*': st.push(p*q); break;
					case '/': st.push(q/p); break;
				}
			}else{
				
				int t = stoi(str);
				st.push(t);
			}
		}
		cout<<st.top()<<endl;
	}	
	
	
	return 0;
}
發佈了1154 篇原創文章 · 獲贊 46 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章