题解 | #逆波兰表达式求值#

逆波兰表达式求值

https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382

#include <string.h>

//字符串形式的数字转int
int StrToInt(char* s) {
    int num = 0, flag = 0;
    if (s[0] == '-') {
        s++;
        flag = 1;
    }
    for (int i = 0;s[i] != '\0';i++)
        num = s[i] - '0' + num * 10;
    return flag ? -num : num;
}

int evalRPN(char** tokens, int tokensLen) {
    // write code here
    int sum = 0;
    int data[10000], no = 0;//粗糙的栈
    for (int i = 0;i < tokensLen;i++) {
        if (!strcmp(tokens[i], "+")) {
            sum = data[no - 2] + data[no - 1];//取栈顶的两个元素运算
            no -= 2;//出栈两个,栈指针减2
            data[no++] = sum;//运算结果入栈
            data[no] = 0;//擦屁股,清零之前出栈的元素
        }
        else if (!strcmp(tokens[i], "-")) {
            sum = data[no - 2] - data[no - 1];
            no -= 2;
            data[no++] = sum;
            data[no] = 0;
        }
        else if (!strcmp(tokens[i], "*")) {
            sum = data[no - 2] * data[no - 1];
            no -= 2;
            data[no++] = sum;
            data[no] = 0;
        }
        else if (!strcmp(tokens[i], "/")) {
            sum = data[no - 2] / data[no - 1];
            no -= 2;
            data[no++] = sum;
            data[no] = 0;
        }
        else {
            data[no++] = StrToInt(tokens[i]);
        }
    }
    return data[0];
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
2
收藏
分享
牛客网
牛客企业服务