题解 | #牛的表达式计算器#

牛的表达式计算器

https://www.nowcoder.com/practice/261e7f01438f414c92f59c0059d3a906

考察知识点:栈,数组

解题分析: 这个道题的解法,我们可以通过观察题目得出,如果遇到‘+’‘-’‘*’‘/’其中一种的时候,我们将当前符号前面的两个数字做运算,之后又放回数组中,等待下次的运算。所有这道题可以用栈来实现,流程如下

1、如果遇到的是非‘+’‘-’‘*’‘/’等符号时,我们就将当前的数组转为int类型,并压入栈中

2、当遇到‘+’‘-’‘*’‘/’时,就从栈中连续取出两个做对应的运算,之后将得出的结果再次压入栈中,等待下次运算

3、对于返回的值,应该用栈顶的值做返回值 ,因为有些公式运算并不是完整的,可能出现运算符不能所有的值都运算完成

编程语言:C

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param tokens string字符串一维数组 
 * @param tokensLen int tokens数组长度
 * @return int整型
 */
#include <string.h>
int calculatePostfix(char** tokens, int tokensLen ) {
    int sum = 0, tmp = 0;
    int stack[1000] = {0}, count = 0;
    
    for (int i = 0; i < tokensLen; i++) {
        if (strcmp(tokens[i],"*") == 0) {	//遇到运算符,就执行运算操作
            tmp = stack[--count];
            sum = stack[--count];		// 连续从栈中取出两个值
            sum = tmp * sum;;		// 做运算
            stack[count++] = sum;		// 压回栈中
        } else if (strcmp(tokens[i], "/") == 0) {
            tmp = stack[--count];
            sum = stack[--count];
            sum = sum / tmp;
            stack[count++] = sum;
        } else if (strcmp(tokens[i], "+") == 0) {
            tmp = stack[--count];
            sum = stack[--count];
            sum = sum + tmp;
            stack[count++] = sum;
        } else if (strcmp(tokens[i], "-") == 0) {
            tmp = stack[--count];
            sum = stack[--count];
            sum = sum - tmp;
            stack[count++] = sum;
        } else {
            stack[count++] = atoi(tokens[i]);		// 如果遇到数字,就转为int类型,并压入栈中
        }
    }

    return stack[--count];
}

面试高频TOP202解析 文章被收录于专栏

采用Java,C,Python等方法去解答面试高频TOP202题目,

全部评论

相关推荐

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