C++ Infix Expression Evaluation/Stack Application

topic:

Given an expression, where operators only include +,-,*,/(addition, subtraction, multiplication, and division), and may contain parentheses, please find the final value of the expression.

Note:
Data guarantees that the given expression is valid.
The topic guarantees that the symbol - will only appear as a minus sign and will not appear as a minus sign. For example, expressions such as -1+2, will not appear. The question guarantees that all numbers in the expression are positive integers. The title guarantees that the expression does not exceed 2 31 − 1 2^{31}−1 in the intermediate calculation process and the result(2+2)*(-(1+1)+2)

2311 .
The divisibility in the title refers to rounding to 0, that is to say, rounding down for results greater than 0, such as 5/3=1, and rounding up for results less than 0, such as 5/(1−4)=−1 .
The integer division in C++ and Java is rounded to zero by default; the integer division in Python // is rounded down by default, so the integer division in Python's eval() function is also rounded down, which cannot be used directly in this question.

Input format
A total of one line, for the given expression.

The output format
is a total of one line, which is the result of the expression.

Data Range
The length of the expression does not exceed 1 0 5 10^5105

Input sample:
(2+2)*(1+1)
Output sample:
8

C++ code template:

#include<iostream>
#include<cstring>
#include<stack>
#include<unordered_map>

using namespace std;

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

void eval(){
    
    
    // 读取num中前两个数,注意a,b的顺序不能反
    int b = num.top();
    num.pop();
    int a = num.top();
    num.pop();
    int x = 0;
    char c = op.top();
    op.pop();
    if(c == '+'){
    
    
        x = a + b;
    }
    else if(c == '-'){
    
    
        x = a - b;
    }
    else if(c == '*') x = a * b;
    else x = a / b;
    num.push(x);
}

int main(){
    
    
    //1.定义优先级
    unordered_map<char, int> pr{
    
    {
    
    '+',1},{
    
    '-',1},{
    
    '*', 2},{
    
    '/',2}};
    //2.读字符串
    string str;
    cin >> str;
    for(int i = 0; i < str.size(); i++){
    
    
        auto c = str[i];
        // c是数字
        if(isdigit(c)){
    
    
            int x = 0, j = i;
            while(j < str.size() && isdigit(str[j])) 
                x = x * 10 + str[j++] - '0';
            i = j - 1;//最后跳出循环时,j是第一位不是数字的下标
            num.push(x);
        }
        // c是'('
        else if(c == '(') op.push(c);
        // c是 ')'
        else if(c == ')'){
    
    
            while(op.top() != '(') eval();
            op.pop();
        }
        // c是操作符
        else{
    
    
            while(op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval();
            op.push(c);
        }
    }
    //3. 计算
    while(op.size()) eval();
    cout << num.top() << endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43943476/article/details/126913877