算法竞赛进阶指南---0x18(栈)表达式计算4

题面

在这里插入图片描述

题解

  1. 括号序列,表达式的计算几乎都是离不开栈的,对于表达式的计算,我们可以用两个栈来分别存储数字和字符,然后求解
  1. 规则: 每次遍历到运算符时,比较当前运算符和栈顶运算符的优先级,只要是栈顶优先级大于等于当前优先级,那么就可以将前面的式子计算 ,具体细节看代码

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>

using namespace std;

stack<int> nums;
stack<char> opt;

int qmi(int m, int k) {
    
    
    int res = 1;
    while (k) {
    
    
        if (k & 1) res = res * m;
        m = m * m;
        k >>= 1;
    }
    return res;
}

void cal() {
    
    
    int a = nums.top();
    nums.pop();
    int b = nums.top();
    nums.pop();
    char c = opt.top();
    opt.pop();
    int res;
    if (c == '+') res = b + a;
    if (c == '-') res = b - a;
    if (c == '*') res = b * a;
    if (c == '/') res = b / a;
    if (c == '^') res = qmi(b, a);
    nums.push(res);
}

int main() {
    
    

    string str;
    cin >> str;

    if (str[0] == '-') str = '0' + str;   //将式子转化规范

    //出现多余括号处理
    string left;
    for (int i = 0; i < str.size(); i++) left += '(';
    str = left + str + ')';

    for (int i = 0; i < str.size(); i++) {
    
    
        if (str[i] >= '0' && str[i] <= '9') {
    
    
            int j = i, t = 0;
            while (str[j] >= '0' && str[j] <= '9') {
    
    
                t = t * 10 + str[j] - '0';
                j++;
            }
            nums.push(t);
            i = j - 1;
        } else {
    
    
            char c = str[i];
            if (c == '(') opt.push(c);
            else if (c == '+' || c == '-') {
    
    
                //'-' 是负号的情况
                if (c == '-' && !(str[i - 1] >= '0' && str[i - 1] <= '9') && str[i - 1] != ')') {
    
    
                    // 将-(...)变成-1 * (...)
                    if (str[i + 1] == '(') {
    
    
                        nums.push(-1);
                        opt.push('*');
                    } else {
    
    
                        int j = i + 1, t = 0;
                        while (str[j] >= '0' && str[j] <= '9') {
    
    
                            t = t * 10 + str[j] - '0';
                            j++;
                        }
                        nums.push(-t);
                        i = j - 1;
                    }
                } else {
    
       // '-'是减号的情况
                    while (opt.top() != '(') cal();
                    opt.push(c);
                }
            } else if (c == '*' || c == '/') {
    
    
                while (opt.top() == '*' || opt.top() == '/' || opt.top() == '^') cal();
                opt.push(c);
            } else if (c == '^') {
    
    
                while (opt.top() == '^') cal();
                opt.push(c);
            } else if (c == ')') {
    
    
                while (opt.top() != '(') cal();
                opt.pop();
            }
        }
    }
    cout << nums.top() << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/113980212