MT3033 新的表达式

代码: 

#include <bits/stdc++.h>
using namespace std;
bool is_op(char c)
{
    return c == '&' || c == '|';
}
int priority(char op)
{ // 运算优先级。如果有+-*/等别的运算符,则这个函数很有必要
    if (op == '&' || op == '|')
    {
        return 1;
    }
    return -1;
}
void process_op(stack<int> &st, char op)
{ // 处理单次运算
    int r = st.top();
    st.pop();
    int l = st.top();
    st.pop();
    switch (op)
    {
    case '&':
        st.push(min(l, r));
        break;

    case '|':
        st.push(max(l, r));
        break;
    }
}
int evaluate(string &s)
{
    stack<int> st;  // 数字栈
    stack<char> op; // 符号栈
    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == '(')
        {
            op.push(s[i]);
        }
        else if (s[i] == ')') // 运算
        {
            while (op.top() != '(') // 一直读到(
            {                       // 计算一次即可,因为下一个else if会将多个需要计算的式子合并成一次计算
                process_op(st, op.top());
                op.pop();
            }
            op.pop(); //)出栈
        }
        else if (is_op(s[i])) // & |
        {
            char cur_op = s[i];
            while (!op.empty() && priority(op.top()) >= priority(cur_op))
            {                             // 运算符栈是否为空,并判断优先级
                process_op(st, op.top()); // 如果栈顶优先级>=当前优先级,则把栈顶的计算完
                op.pop();                 // 例如(1&2|3),读到|时,栈顶是&,&的优先级>=|,所以先计算&,再计算|
            }
            op.push(cur_op);
        }
        else
        { // 数字
            int number = 0;
            while (i < s.size() && isdigit(s[i]))
            {
                number = number * 10 + s[i++] - '0';
            }
            i--;
            st.push(number);
        }
    }
    while (!op.empty())
    {
        process_op(st, op.top());
        op.pop();
    }
    return st.top();
}

int main()
{
    string s;
    cin >> s;
    cout << evaluate(s) << endl;
    return 0;
}

类似题目:

MT3034算术招亲

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值