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

经典算法 表达式求值

表达式求值

问题描述

给你一个只包含+-*/0123456789的字符串求出该字符串所代表的表达式的值。这里的除法,为了简便,为整数除法,所以答案一定也是一个整数。保证0不作被除数。

示例输入

(1+6*(14+1))+((1+3)*(7+4))*3+7

示例输出

230

示例输入

5/2

示例输出

2

c++代码

#include<bits/stdc++.h>
#include<ctype.h>
#include<string.h>using namespace std;string infix_expression, mid;
vector<string> postfix_expression;int main() {cin >> infix_expression;stack<string> st;for (char b : infix_expression) {string a(1, b);if (!isdigit(b) && mid.size() > 0) postfix_expression.push_back(mid), mid.clear();if (a == "+" || a == "-") {while(!st.empty() && st.top() != "(") postfix_expression.push_back(st.top()), st.pop();}else if (a == "*" || a == "/") {while(!st.empty() && (st.top() == "*" || st.top() == "/")) postfix_expression.push_back(st.top()), st.pop();}else if (a == ")") {while(!st.empty() && st.top() != "(") postfix_expression.push_back(st.top()), st.pop();st.pop();}if (a != ")" && !isdigit(b)) st.push(a);if (isdigit(b)) mid += a;}if (mid.size() > 0) postfix_expression.push_back(mid), mid.clear();while(!st.empty()) postfix_expression.push_back(st.top()), st.pop();stack<int> sk;for (string s : postfix_expression) {int a = 0, b = 0, c = 0;if (s == "+" || s == "-" || s == "*" || s == "/") {a = sk.top(), sk.pop(), b = sk.top(), sk.pop();if (s == "+") c = b + a;else if (s == "-") c = b - a;else if (s == "*") c = b * a;else if (s == "/") c = b / a;}else c = stoi(s);sk.push(c);}cout << sk.top();return 0;
}//by wqs

相关文章:

  • DEA-Net:基于细节增强卷积和内容引导注意力的单图像去雾
  • 基础理论学习参考
  • 在 Debian 10.x 安装和配置 Samba
  • 论文笔记(七十八)Do generative video models understand physical principles?
  • 2024新版仿蓝奏云网盘源码,已修复已知BUG,样式风格美化,可正常运营生产
  • LeetCode第158题_用Read4读取N个字符 II
  • C语言之机房机位预约系统
  • AIGC(生成式AI)试用 30 -- AI做软件程序测试 1
  • Day58 | 179. 最大数、316. 去除重复字母、334. 递增的三元子序列
  • 插叙的作用
  • 安全技术和防火墙
  • Python 项目环境配置与 Vanna 安装避坑指南 (PyCharm + venv)
  • 《银行数字化风控-业务于实战》读后知识总结
  • 算法—插入排序—js(小数据或基本有序数据)
  • 八大排序之希尔排序
  • StringEscapeUtils:给你的字符串穿上“防弹衣“——转义工具类深度解析
  • 【Rust 精进之路之第6篇-流程之舞】控制流:`if/else`, `loop`, `while`, `for` 与模式匹配初窥
  • PFLM: Privacy-preserving federated learning with membership proof证明阅读
  • 最新iOS性能测试方法与教程
  • 秘密任务 3.0:如何通过 JWT 认证确保 WebSockets 安全
  • 分离19年后:陈杨梅首度露面,父亲亲手喂棉花糖给女儿吃
  • AI时代教育如何变革?上海首批 “标准化家长学校”出炉
  • 春山谷雨前,并手摘芳烟
  • 大悦城:去年净亏损29.77亿元,三年累计亏损超70亿元
  • 长三角铁路五一假期预计发送旅客2880万人次,同比增6%
  • 广西东兰官方通报“村民求雨耕种”:摆拍,恶意炒作