题解 | 计算表达式

计算表达式

https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b

#include <iostream>
#include<stack>

using namespace std;

bool opPriority(char op1, char op2) {
    if ((op1 == '/' || op1 == '*') && (op2 == '-' || op2 == '+'))return true;
    return false;
}

double caculate(double a, double b, char op) {
    switch (op) {
        case '-':
            return a - b;
        case '+':
            return a + b;
        case '/':
            return a / b;
        case '*':
            return a * b;
    }
    return 0;
}

int main() {
    string s;
    while (cin >> s) { // 注意 while 处理多个 case
        stack<double>numstack;
        stack<char>opstack;
        for (int i = 0; i < s.length();) {
            double num = 0;
            int flag=1;
            if(i==0&&s[i]=='-'){
                flag=-1;
                i++;
            }
            if(isdigit(s[i])){
                while (isdigit(s[i])) {
                    num = num * 10 + s[i] - '0';
                    i++;
                }
                if(flag==-1)num=-num;
                numstack.push(num);
            }else if (opstack.empty() || opPriority(s[i], opstack.top())){
                opstack.push(s[i]);
                i++;
            }else {
                while (!opstack.empty() && !opPriority(s[i], opstack.top())) {
                    double a = numstack.top();numstack.pop();
                    double b = numstack.top();numstack.pop();
                    numstack.push(caculate(b, a, opstack.top()));
                    opstack.pop();
                }
                opstack.push(s[i]);
                i++;
            }
        }
        while(!opstack.empty()){
            double a=numstack.top();numstack.pop();
            double b=numstack.top();numstack.pop();
            numstack.push(caculate(b, a, opstack.top()));opstack.pop();
        }
        cout<<numstack.top()<<endl;

    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务