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

牛的表达式计算器

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

一、知识点:

二、文字分析:

  1. 创建一个空栈。
  2. 遍历后缀表达式的每个元素:如果元素是操作数,将其转换为整数并将其压入栈中。如果元素是运算符,从栈中弹出两个操作数,进行相应的运算,并将结果压入栈中。
  3. 遍历结束后,栈中只剩下一个元素,即为后缀表达式的计算结果。

三、编程语言:

java

四、正确代码:

import java.util.*;


public class Solution {
    public int calculatePostfix(String[] tokens) {
        Stack<Integer> stack = new Stack<>();

        for (String token : tokens) {
            if (token.equals("+") || token.equals("-") || token.equals("*") ||
                    token.equals("/")) {
                int operand2 = stack.pop();
                int operand1 = stack.pop();
                stack.push(compute(token, operand1, operand2));
            } else {
                stack.push(Integer.parseInt(token));
            }
        }

        return stack.pop();
    }

    private int compute(String operator, int operand1, int operand2) {
        switch (operator) {
            case "+":
                return operand1 + operand2;
            case "-":
                return operand1 - operand2;
            case "*":
                return operand1 * operand2;
            case "/":
                return operand1 / operand2;
        }

        return 0;
    }
}

全部评论

相关推荐

05-30 12:03
山西大学 C++
offer来了我跪着接:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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