题解 | #后缀表达式求值#

后缀表达式求值

http://www.nowcoder.com/practice/22f9d7dd89374b6c8289e44237c70447

import java.util.*;


public class Solution {
    /**
     * 
     * @param tokens string字符串一维数组 
     * @return int整型
     */
    
    public int evalRPN(String[] tokens) {
        Stack<Integer> result = new Stack<>();//创建栈
        for (String x : tokens) {//遍历每一个输入,注意是字符串类型
            if (x.equals("+") || x.equals("-") || x.equals("*") || x.equals("/")) {//如果当前字符串是操作符
                if (result.size() < 2) return 0;//如果栈内数字不足两个,即无法进行运算,则返回0
                //依次将栈内两个数字出栈进行操作运算
                int a = result.pop();
                int b = result.pop();
                int c = 0;//用c表示每次运算的结果
                if (x.equals("+")) c = b + a;
                if (x.equals("-")) c = b - a;
                if (x.equals("*")) c = b * a;
                if (x.equals("/")) c = b / a;
                result.push(c);//将结果入栈
            } else {//如果当前字符串是数字
                result.push(Integer.valueOf(x));//操作数入栈,注意先将string字符串转为char字符,再转为int数字
            }
        }
        int resultInt = result.pop();
        return resultInt;
    }
}
全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务