表达式计算

· · 个人记录

此篇文章会教会你栈的拓展,表达式求值。

读此文章之前你得先学会栈。

正文

The first step

先考虑如此问题。

如果一个表达式只有加与减。

如 1+22-3+89-6+114-514。

那怎么计算呢。

我们可以用栈将运算符和运算数分开存,然后统一计算。

代码。

#include<bits/stdc++.h>
using namespace std;
stack<int>st,op;
void solve(){
    int x=st.top();
    st.pop();
    int y=st.top();
    st.pop();
    int z=op.top();
    op.pop();
    if(z=='+') st.push(x+y);
    if(z=='-') st.push(y-x);
}
int main() {
    string s;
    cin>>s;
    for(int i=0;i<s.size();i++){
        char ch=s[i];
        if(isdigit(ch)){
            int p=ch-'0',j=i+1;
            while(isdigit(s[j])) p=p*10+s[j]-'0',j++;
            i=--j;
            st.push(p);
            if(!op.empty()) solve();
        }
        else
            op.push(ch);
    }
    cout<<st.top();
    return 0; 
} 

The second step

如果乘除混入了呢。(除表示整除)

类似于 [NOIP2013 普及组] 表达式求值.

我们需要考虑优先级问题。