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

牛的表达式计算器

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

思路:

  1. 如果是数字,则压栈
  2. 如果是操作符,则出栈两个操作数,将运算结果继续压栈
  3. 最终的栈中只会有一个数字,就是结果

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param tokens string字符串一维数组 
     * @return int整型
     */
    public int calculatePostfix (String[] tokens) {
        Stack<Integer> s = new Stack<>();
        // write code here
        for(String t : tokens){
            if("+".equals(t)){
                s.push(s.pop() + s.pop());
            }else if("-".equals(t)){
                Integer t2 = s.pop();
                Integer t1 = s.pop();
                s.push(t1 - t2);
            }else if("*".equals(t)){
                s.push(s.pop() * s.pop());
            }else if("/".equals(t)){
                Integer divide =s.pop();
                Integer dividend = s.pop();
                s.push(dividend / divide);
            }else{
                // 数字,压栈
                s.push(Integer.parseInt(t));
            }
        }

        return s.pop();
    }
}

全部评论

相关推荐

小覃1:硕士了还投助理岗位吗,一般不都直接干工程师了吗
点赞 评论 收藏
分享
02-26 16:52
门头沟学院 Java
Lunarloop:董事长亲自到ssob来要IM项目的技术方案来了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务