0
点赞
收藏
分享

微信扫一扫

Day03---栈--给定一个逆波兰表达式,求表达式的值

皮皮球场 2022-04-13 阅读 70
java

 

 

 /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param tokens string字符串一维数组 
     * @return int整型
     */
    public int evalRPN (String[] tokens) {
        // write code here
        Stack<Integer> stack = new Stack();
        for(int i = 0; i<tokens.length; i++){
            String str = tokens[i];
            /**
             * 判断是否是符号,不是则入栈
             * 是则计算,再把结果入栈
             */
            if(str.equals("+")){
                int a = stack.pop();
                int b = stack.pop();
                stack.push(b + a);
            }else if(str.equals("-")){
                int a = stack.pop();
                int b = stack.pop();
                stack.push(b - a);
            }else if(str.equals("*")){
                int a = stack.pop();
                int b = stack.pop();
                stack.push(a * b);
            }else if(str.equals("/")){
                int a = stack.pop();
                int b = stack.pop();
                stack.push(b / a);
            }else {
                stack.push(Integer.parseInt(str));
            }
        }
        return stack.pop();
    }
举报

相关推荐

0 条评论