#include <iostream> #include <cstdio> // 相当于C语⾔⾥⾯的#include <stdio.h> #include <cstdlib> // 相当于C语⾔⾥⾯的#include <stdib.h> #include <cstring> #include<stack> using namespace std; int priority(char a,char b){ if((a=='+'||a=='-')&&(b=='+'||b=='-')) return 1; if((a=='+'||a=='-')&&(b=='*'||b=='/')) return -1; if((a=='*'||a=='/')&&(b=='+'||b=='-')) return 1; if((a=='*'||a=='/')&&(b=='*'||b=='/')) return 1; if((a=='+'||a=='-'||a=='*'||a=='/')&& b=='(') return -1; if(a=='(' && b==')') return 0; if(a=='('&& b!=')') return -1; if(b==')') return -2; return 0; } int caculate(int a,char c,int b){ if(c=='+') return a+b; if(c=='-') return a-b; if(c=='*') return a*b; if(c=='/') return a/b; return 0; } int main(){ string e; getline(cin,e); stack<int>n; stack<char>a; for(string::iterator it=e.begin();it!=e.end();++it) { if((*it)>='0'&& (*it)<='9') { int number=(int)((*it)-'0'); string::iterator p=it; while((*(p+1))>='0' && (*(p+1))<='9') { number=number*10+(int)((*(p+1))-'0'); p++; } it=p; n.push(number); } else{ if(a.empty()) { a.push((*it)); continue; } else { if(priority(a.top(),(*it))==-1) { a.push((*it)); continue; } if(priority(a.top(),(*it))==1) { while(priority(a.top(),(*it))==1) { int p=n.top();n.pop(); int q=n.top(); n.pop(); char c=a.top();a.pop(); n.push(caculate(q,c,p)); if(a.empty()){ break; } } a.push((*it)); continue; } if(priority(a.top(),(*it))==0) { a.pop();continue; } if(priority(a.top(),(*it))==-2) { while(a.top()!='(') { int p=n.top();n.pop(); int q=n.top();n.pop(); char c=a.top();a.pop(); n.push(caculate(q,c,p)); } a.pop();continue; } } } } while(!a.empty()){ int p=n.top(); n.pop(); int q=n.top(); n.pop(); char c=a.top(); a.pop(); n.push(caculate(q,c,p)); } cout<<n.top()<<endl; }
#include<bits/stdc++.h> using namespace std; const int N =1E6+10; stack<int> num; //操作数 stack<char> op; //操作符 //优先级表 unordered_map<char, int> h{ {'+', 1}, {'-', 1}, {'*',2}, {'/', 2} }; void equal() { int a=num.top();num.pop(); //弹出 int b=num.top();num.pop(); //弹出 char p=op.top();op.pop(); //弹出 int r=0; if(p=='+') r=a+b; if(p=='-') r=b-a; if(p=='*') r=a*b; if(p=='/') r=b/a; //读入 num.push(r); } void solve(){ string s;cin >> s; for(int i=0;i<s.size();i++) { if(s[i]>='0' && s[i]<='9') { //读入 int a=0,j=i; while(s[j]>='0' && s[j]<='9' && j<s.size()) { a=a*10+s[j]-'0'; ++j; } num.push(a); i=j-1; } else if(s[i]=='(') { //直接进站 op.push(s[i]); } else if(s[i]==')') { //直接进入计算 while(op.top()!='(') equal(); op.pop(); //出左括号 } else { while(op.size() && h[op.top()]>=h[s[i]]) { equal(); } op.push(s[i]); //新的入栈 } } //然后算没有算完的 while(op.size()) { equal(); //剩余的计算 } //输出队头元素 cout << num.top() << endl; return; } int main(void){ solve(); return 0; }