acwing 自我学习笔记-表达式求值 3302

给定一个表达式,其中运算符仅包含 +,-,*,/(加 减 乘 整除),可能包含括号,请你求出表达式的最终值。

注意:

  • 数据保证给定的表达式合法。
  • 题目保证符号 - 只作为减号出现,不会作为负号出现,例如,-1+2,(2+2)*(-(1+1)+2) 之类表达式均不会出现。
  • 题目保证表达式中所有数字均为正整数。
  • 题目保证表达式在中间计算过程以及结果中,均不超过 231−1231−1。
  • 题目中的整除是指向 00 取整,也就是说对于大于 00 的结果向下取整,例如 5/3=15/3=1,对于小于 00 的结果向上取整,例如 5/(1−4)=−15/(1−4)=−1。
  • C++和Java中的整除默认是向零取整;Python中的整除//默认向下取整,因此Python的eval()函数中的整除也是向下取整,在本题中不能直接使用。

输入格式

共一行,为给定表达式。

输出格式

共一行,为表达式的结果。

数据范围

表达式的长度不超过 105105。

输入样例:

(2+2)*(1+1)

输出样例:

8

#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <unordered_map>
#include <cstring>
using namespace std;

stack<int> num;//数据栈
stack<char> op;//操作栈

void Operator()
{
    int a = num.top();
    num.pop();
    int b = num.top();
    num.pop();
    char c = op.top();
    op.pop();
    int x;
    if (c == '+')
    {
        x = a + b;
    }
    else if (c == '-')
    {
        x = b - a;
    }
    else if (c == '*')
    {
        x = a * b;
    }
    else
    {
        x = b / a;
    }
    num.push(x);

}

int main()
{
    unordered_map<char, int> pre{ {'+',1},{'-',1},{'*',2},{'/',2}};//设定运算优先级
    string str;
    cin >> str;
    for (int i = 0; i < str.size(); i++)
    {
        if (isdigit(str[i]))
        {
            int j = i,x=0;
            while (j < str.size() && isdigit(str[j]))
            {
                x = x * 10 + (str[j] - '0');
                j++;
            }
            i = j - 1;
            num.push(x);
        }
        else if (str[i] == '(')
        {
            op.push(str[i]);
        }
        else if (str[i] == ')')
        {
            while (op.top() != '(')
            {
                Operator();
            }
            op.pop();
        }
        else
        {
            while (op.size() && op.top() != '(' && pre[op.top()] >= pre[str[i]])
            {
                Operator();
            }
            op.push(str[i]);
        }
    }
    while (op.size())
    {
        Operator();
    }
    cout << num.top() << endl;
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值