蓝桥杯 算法训练 表达式计算(栈的应用)

来源:互联网 发布:vb key value 编辑:程序博客网 时间:2024/06/05 21:00

问题描述

  输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。

输入格式

  输入一行,包含一个表达式。

输出格式

  输出这个表达式的值。

样例输入

1-2+3*(4-5)

样例输出

-4

数据规模和约定

  表达式长度不超过100,表达式运算合法且运算过程都在int内进行。

思路:

两个栈,一个存数字,一个存运算符,扫描字符串,当当前运算符优先级小于栈顶运算符时,对上一次存入进行运算操作。

代码

#include<iostream>#include<stack>#include<ctype.h>#include<cstring>using namespace std;stack<int> num;stack<char> st;char s[150];int solve() {    int a = num.top();num.pop();    int b = num.top();num.pop();    if(st.top() == '-') return b-a;    if(st.top() == '+') return a+b;    if(st.top() == '*') return a*b;    if(st.top() == '/') return b/a;}int main() {    ios::sync_with_stdio(false);    cin >> s;    int i = 0;    while(i < strlen(s)) {        if(isdigit(s[i])) {            int t = 0;            while(i < strlen(s) && isdigit(s[i])) {                t = 10 * t + (s[i] - '0');                i++;            }            num.push(t);        }        else if(s[i] == '(') st.push(s[i++]);        else if(s[i] == '+' || s[i] == '-') {            if(st.empty() || st.top() == '(') {                st.push(s[i++]);            } else {                int t = solve();                num.push(t);                st.pop();                st.push(s[i++]);            }        }        else if(s[i] == '*' || s[i] == '/') {             if(st.empty() || st.top() == '(' || st.top() == '+' || st.top() == '-') st.push(s[i++]);            else {                    int t = solve();                    num.push(t);                    st.pop();                    st.push(s[i++]);            }        }        else if(s[i] == ')') {            while(st.top() != '(') {                int t = solve();                num.push(t);                st.pop();            }            st.pop();            i++;        }    }    while(st.size() > 1) {        int t = solve();        num.push(t);        st.pop();    }    cout << solve() << endl;    return 0;}