题解 | 计算表达式

计算表达式

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")

全部评论

相关推荐

好像有点准
我推的MK:感觉这个表格呢好像有用又好像没用,真有offer了不管加班多么严重也得受着,没offer管他加班什么样也只能看看,反正轮不到我选
点赞 评论 收藏
分享
野猪不是猪🐗:现在的环境就是这样,供远大于求。 以前卡学历,现在最高学历不够卡了,还要卡第一学历。 还是不够筛,于是还要求得有实习、不能有gap等等... 可能这个岗位总共就一个hc,筛到最后还是有十几个人满足这些要求。他们都非常优秀,各方面都很棒。 那没办法了,看那个顺眼选哪个呗。 很残酷,也很现实
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务