问题描述
输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。
输入格式
输入一行,包含一个表达式。
输出格式
输出这个表达式的值。
样例输入
1-2+3*(4-5)
样例输出
-4
数据规模和约定
表达式长度不超过100,表达式运算合法且运算过程都在int内进行。
#include<iostream> #include<cstdio> #include<stack> #include<vector> #include<cstring> #include<cctype> using namespace std; //#define LOCAL struct Node { int key; // 为0时表示当前节点为操作数,为1表示为操作符; int number; char oper; }a[105]; //存放拆解后的表达式 stack<Node> analytic; stack<Node> calc; //存放后序表达式 vector<Node> post; int main() { #ifdef LOCAL freopen("algo_156.txt", "r", stdin); #endif string str; int num_a = 0; cin >> str; //解决负数开头的问题 if(str[0] == ‘-‘) { string str1 = "0"; str = str1 + str; } //解析表达式 int len = str.length(); for(int i = 0; i < len; i++) { int num = 0; int temp = 0; while(str[i] != ‘\0‘ && isdigit(str[i])) { temp = 1; num *= 10; num += (str[i] - ‘0‘); i++; } if(temp == 1) { a[num_a].key = 0; a[num_a].number = num; post.push_back(a[num_a]); num_a++; } if(str[i] == ‘(‘) { a[num_a].key = 1; a[num_a].oper = ‘(‘; analytic.push(a[num_a]); num_a++; } else if(str[i] == ‘)‘) { while(!analytic.empty() && analytic.top().oper != ‘(‘) { post.push_back(analytic.top()); analytic.pop(); } if(analytic.top().oper == ‘(‘) analytic.pop(); } else if(str[i] == ‘+‘ || str[i] == ‘-‘) { while(!analytic.empty() && analytic.top().oper != ‘(‘) { post.push_back(analytic.top()); analytic.pop(); } a[num_a].key = 1; a[num_a].oper = str[i]; analytic.push(a[num_a]); num_a++; } else if(str[i] == ‘*‘ || str[i] == ‘/‘) { while(!analytic.empty() && (analytic.top().oper == ‘*‘ || analytic.top().oper == ‘/‘)) { post.push_back(analytic.top()); analytic.pop(); } a[num_a].key = 1; a[num_a].oper = str[i]; analytic.push(a[num_a]); num_a++; } } //将栈中元素释放 while(!analytic.empty()) { post.push_back(analytic.top()); analytic.pop(); } //输出后序表达式 /* for(int m = 0; m < post.size(); m++) { if(post[m].key == 1) cout << post[m].oper; else cout << post[m].number; } cout << endl; */ //计算后序表达式 for(int j = 0; j < post.size(); j++) { if(post[j].key == 0) { calc.push(post[j]); } else if(post[j].key == 1) { int s, left, right; right = calc.top().number; calc.pop(); left = calc.top().number; switch(post[j].oper) { case ‘+‘ : s = left + right;break; case ‘-‘ : s = left - right;break; case ‘*‘ : s = left * right;break; case ‘/‘ : s = left / right;break; default : return -1; } calc.top().number = s; } } int sum = calc.top().number; cout << sum << endl; return 0; }