表达式计算4(牛客板子,+-*/^)***

表达式计算4

#include<bits/stdc++.h>
using namespace std;
 
stack<char> ops;
stack<int> num;
unordered_map<char, int> mp = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'^', 3}};
 
int ksm(int x, int k){
    int res = 1;
    while(k){
        if(k & 1) res *= x;
        x *= x;
        k >>= 1;
    }
    return res;
}
void eval(){
    int b = num.top(); num.pop();
    int a = num.top(); num.pop();
    char c = ops.top(); ops.pop();
    if(c == '+') num.push(a + b);
    else if(c == '-') num.push(a - b);
    else if(c == '*') num.push(a * b);
    else if(c == '/') num.push(a / b);
    else num.push(ksm(a, b));
}

signed main(){
    string s, str; cin>>s;
    for(int i = 0; i < s.size(); ++i) str += '(';
    s = str + s + ')';//应对多余括号(处理右括号多,左括号多无所谓)
    
    for(int i = 0; i < s.size(); ++i){
        if(s[i] >= '0' && s[i] <= '9'){
            int j = i, t = 0;
            while(s[j] >= '0' && s[j] <= '9'){t = t * 10 + s[j] - '0'; ++j;};
            num.push(t);
            i = j - 1;
        }else if(s[i] == '(') ops.push('(');
        else if(s[i] == ')'){
            while(ops.top() != '(') eval(); ops.pop();
        }else if(s[i] == '-' && !(s[i-1] >= '0' && s[i-1] <= '9' || s[i-1] == ')')){ //判断负数
            if(s[i+1] == '('){ //负数且下一个是'('
                num.push(-1); ops.push('*');
            }else{
                int j = i + 1, t = 0;
                while(s[j] >= '0' && s[j] <= '9'){t = t * 10 + s[j] - '0'; ++j;};
                num.push(-t);
                i = j - 1;
            }
            
        }else{
            while(ops.size() && mp[ops.top()] >= mp[s[i]]) eval();
            ops.push(s[i]);
        }
    }
    
    cout << num.top();
    
    return 0;
}
posted @ 2025-03-18 20:27  awei040519  阅读(9)  评论(0)    收藏  举报