求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +, -, *,/ 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
/* 思路: 碰到不是+*-/就转换为整数压栈, 碰到了就弹出两个数进行运算,得到的结果再压栈。最后压出最后的值 */ public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> s = new Stack<Integer>(); String operators = "+-*/"; for(String token : tokens){ if(!operators.contains(token)){ s.push(Integer.valueOf(token)); continue;//不能用break } int a = s.pop(); int b = s.pop(); if(token.equals("+")) { s.push(b + a); } else if(token.equals("-")) { s.push(b - a); } else if(token.equals("*")) { s.push(b * a); } else { s.push(b / a); } } return s.pop(); } }
本文介绍了一种通过栈数据结构实现逆波兰表达式计算的方法。文章详细解释了如何解析输入的表达式,并针对不同的运算符执行相应的计算操作。示例包括了基本的加减乘除运算。
2387

被折叠的 条评论
为什么被折叠?



