当前位置: 首页 > article >正文

【算法】3302. 表达式求值

题目

3302. 表达式求值

思路

把数字压入栈后 i = j - 1是因为while最后还有个i++,所以先减去1,才能抵消,下一次才能读下一个字符或数。

代码

#include <iostream>
#include <stack>
#include <string>
#include <unordered_map>
using namespace std;
stack<int> num;
stack<char> op;
unordered_map<char, int> h{ {'+', 1}, {'-', 1}, {'*',2}, {'/', 2} };
void eval()//求值
{
    int a = num.top();//第二个操作数
    num.pop();
    int b = num.top();//第一个操作数
    num.pop();
    char p = op.top();//运算符
    op.pop();
    int r = 0;
    //计算结果
    if (p == '+') r = b + a;
    if (p == '-') r = b - a;
    if (p == '*') r = b * a;
    if (p == '/') r = b / a;
    num.push(r);//结果入栈
}
int main()
{
    string s;//读入表达式
    cin >> s;
    for (int i = 0; i < s.size(); i++)
    {
        if (isdigit(s[i]))//数字入栈
        {
            int x = 0, j = i;
            while (j < s.size() && isdigit(s[j]))
            {
                x = x * 10 + s[j] - '0';
                j++;
            }
            num.push(x);
            i = j - 1;
        }
        else if (s[i] == '(')
        {
            op.push(s[i]);
        }
        else if (s[i] == ')')//右括号
        {
            while(op.top() != '(')
                eval();
            op.pop();//左括号出栈
        }
        else
        {
            while (op.size() && h[op.top()] >= h[s[i]])
                eval();
            op.push(s[i]);
        }
    }
    while (op.size()) eval();
    cout << num.top() << endl;
    return 0;
}

http://www.kler.cn/a/569558.html

相关文章:

  • nginx+keepalived负载均衡及高可用
  • react原理面试题
  • 大语言模型学习
  • 科技赋能筑未来 中建海龙MiC建筑技术打造保障房建设新标杆
  • 【Maven】入门介绍 与 安装、配置
  • Spring 源码硬核解析系列专题(十二):Spring Integration 的消息驱动源码解析
  • nio使用
  • 在 ASP.NET Core 中压缩并减少图像的文件大小
  • SQL命令详解之数据的查询操作
  • SpringBoot Maven快速上手
  • 量子关联特性的多维度探索:五量子比特星型系统与两量子比特系统的对比分析
  • Nodejs-逐行读取文件【简易版】
  • 【第十节】C++设计模式(结构型模式)-Flyweight( 享元)模式
  • Python爬虫:WebAssembly案例分析与爬取实战
  • AWS API Gateway灰度验证实现
  • Difyにおけるデータベースマイグレーション手順
  • 【爬虫基础】第二部分 爬虫基础理论 P2/3
  • 【开源-线程池(Thread Pool)项目对比】
  • 01.01 QT信号和槽
  • FastExcel vs EasyExcel vs Apache POI:三者的全面对比分析