#include <bits/stdc++.h>
using namespace std;
//此方法与视频中的方法不太一致,不是先转化成后缀表达式后再计算
//而是边转换边计算
//先转换再计算缺点:会导致储存后缀表达式的stack内部数字无法辨别是符号还是计算出的结果
//需要另外设计
stack<int> res;
stack<char> sign;
int table[130]={0};//优先级
void init(int table[])
{
table['-']=1;
table['+']=1;
table['*']=2;
table['/']=2;
table['(']=0;
table[')']=0;
}
//这里要注意是&
void cal(stack<int> &res, char sign)
{
int tmp2 = res.top();
res.pop();
int tmp1 = res.top();
res.pop();
if(sign=='-') res.push(tmp1-tmp2);
if(sign=='+') res.push(tmp1+tmp2);
if(sign=='*') res.push(tmp1*tmp2);
if(sign=='/') res.push(tmp1/tmp2);
}
int main()
{
init(table);
string s;
cin>>s;
int len=s.size();
int i=0;
//因为循环中涉及到i的++,所以不用for
while(i<len){
if(isdigit(s[i])){
int tmp=0;
while(i<len &&isdigit(s[i])){
tmp = tmp*10+s[i]-'0';
i++;
}
res.push(tmp);
}
else{
if(s[i]=='-'){
if(i==0 ||s[i-1]=='('){
int tmp=0;
i++;
while(i<len &&isdigit(s[i])){
tmp = tmp*10+s[i]-'0';
i++;
}
res.push(-1*tmp);
}
else{
while(!sign.empty() &&table[s[i]]<=table[sign.top()]){
cal(res, sign.top());
sign.pop();
}
sign.push(s[i]);
i++;
}
}
else{
if(s[i]=='(') sign.push('(');
else if(s[i]==')'){
while(sign.top()!='('){
cal(res, sign.top());
sign.pop();
}
sign.pop();
}
else{
while(!sign.empty() &&table[s[i]]<=table[sign.top()]){
cal(res, sign.top());
sign.pop();
}
sign.push(s[i]);
}
i++;
}
}
}
while(!sign.empty()){
cal(res, sign.top());
sign.pop();
}
cout<<res.top()<<endl;
return 0;
}
EOJ_1024_表达式
最新推荐文章于 2024-09-13 16:27:15 发布