经典算法 表达式求值
表达式求值
问题描述
给你一个只包含+
、-
、*
、/
、0
、1
、2
、3
、4
、5
、6
、7
、8
、9
的字符串求出该字符串所代表的表达式的值。这里的除法,为了简便,为整数除法,所以答案一定也是一个整数。保证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