3302-表达式求值

题目描述

关系

001 ExpressionCompute

内容

给定一个表达式,其中运算符仅包含 +,-,*,/(加减乘整除),可能包含括号,请你求出表达式的最终值。

注意:

输入格式

共一行,为给定表达式。

输出格式

共一行,为表达式的结果。

数据范围

表达式的长度不超过 105

输入样例:

(2+2)*(1+1)

输出样例:

8

问题分析

最初思路

思路分析

执行流程设计

总结

如何将中缀表达式转化为后缀表达式?直接将跟数栈有关的代码全部删掉,改成输出就行了。

代码实现

表达式求值

#include <bits/stdc++.h>
using namespace std;

string s;

stack<int> num;
stack<char> op;

unordered_map<char, int> h{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};

void eval() {
    int b = num.top(); num.pop();
    int a = num.top(); num.pop();
    char c = op.top(); op.pop();
    
    int res = 0;
    if (c == '+') res = a + b;
    if (c == '-') res = a - b;
    if (c == '*') res = a * b;
    if (c == '/') res = a / b;
    
    num.push(res);
}

int main() {
    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();
    return 0;
}

转后缀表达式

#include <bits/stdc++.h>
using namespace std;

string s;
stack<char> op;
unordered_map<char, int> h{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};

void eval() {
    char c = op.top(); op.pop();
    cout << c;
}

int main()
{
    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++;
            }
            i = j - 1;
            cout << x;
        } else if (s[i] == ')') {
            while (op.top() != '(') {
                eval();
            }
            op.pop();
        } else if (s[i] == '(') {
            op.push(s[i]);
        } else {
            while (op.size() && h[s[i]] <= h[op.top()]) {
                eval();
            }
            op.push(s[i]);
        }
    }
    while (op.size()) eval();
    
    
    return 0;
}