题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int getPriority(char op) {
    if (op == '+' || op == '-') return 1;
    if (op == '*' || op == '/') return 2;
    if (op == '(') return 0;
    return 0;
}

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

int solve(char* s) {
    int len = strlen(s);
    int values[len];
    int valIndex = 0;

    char operators[len];
    int opIndex = -1;

    for (int i = 0; i < len; i++) {
        if (s[i] >= '0' && s[i] <= '9') {
            int val = 0;
            while (i < len && s[i] >= '0' && s[i] <= '9') {
                val = val * 10 + (s[i] - '0');
                i++;
            }
            i--;

            values[valIndex++] = val;
        } else if (s[i] == '(') {
            operators[++opIndex] = s[i];
        } else if (s[i] == ')') {
            while (opIndex >= 0 && operators[opIndex] != '(') {
                int b = values[--valIndex];
                int a = values[--valIndex];
                values[valIndex++] = calculate(a, b, operators[opIndex--]);
            }
            opIndex--; // 弹出 '('
        } else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
            while (opIndex >= 0 && getPriority(operators[opIndex]) >= getPriority(s[i])) {
                int b = values[--valIndex];
                int a = values[--valIndex];
                values[valIndex++] = calculate(a, b, operators[opIndex--]);
            }
            operators[++opIndex] = s[i];
        }
    }

    while (opIndex >= 0) {
        int b = values[--valIndex];
        int a = values[--valIndex];
        values[valIndex++] = calculate(a, b, operators[opIndex--]);
    }

    return values[0];
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
_mos_:我以为手抄报简历就已经很顶了,没想到还有表格简历
点赞 评论 收藏
分享
07-02 13:50
闽江学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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