本题要求我们实现一个简单的计算器。
输入输出格式输入一个n,表示要计算的字符串的个数,接下来是n个字符串
数据规模n <= 1e2
算法设计本题的核心类似于中缀表达式转为后缀表达式,因为计算机处理后缀表达式相当简单,只要维护一个栈即可。这里关键是如何进行转化。运算符有优先级,因此我们维护unordered_map
#include题目链接using namespace std; using gg = long long; gg compute(gg a, gg b,char c){ if(c == '+') return a+b; if(c == '-') return a-b; if(c == 'x') return a*b; if(c == '/') return a/b; } int main() { ios::sync_with_stdio(false); cin.tie(0); gg n; cin>>n; string s; unordered_map um{{'+',0},{'-',0},{'x',1},{'/',1}}; //优先级 while(n--){ cin>>s; stack op; // 操作符栈 stack num; // 操作数栈 for(auto i : s){ if(isdigit(i)) num.push(i - '0'); else { while(not op.empty() and um[op.top()] >= um[i]){ // 进行计算 gg a = num.top(); num.pop(); gg b = num.top(); num.pop(); num.push(compute(b,a,op.top())); // 注意操作数顺序,小心除法 op.pop(); } op.push(i); } } while(not op.empty()){ gg a = num.top(); num.pop(); gg b = num.top(); num.pop(); num.push(compute(b,a,op.top())); op.pop(); } cout<< (num.top() == 24 ? "Yesn" : "Non"); } return 0; }



