evaluate reverse polish notation

快来打我* 2022-02-25 17:14 232阅读 0赞

【题目】
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,,/. Each operand may be an integer or another expression.
Some examples:
[“2”, “1”, “+”, “3”, “
“] -> ((2 + 1) * 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6
【译】
用反波兰符号计算算术表达式的值。
有效的运算符有+、-、、/。每个操作数可以是整数或其他表达式。
例子
[“2”, “1”, “+”, “3”, “
“] -> ((2 + 1) * 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6
【思路】
遍历字符串,如果不是加减乘除符号,就进栈。如果遇到加减乘除,符号前的两个数就出栈,并进行运算再压栈。
【实现】

  1. import java.util.Stack;
  2. public class Solution {
  3. public int evalRPN(String[] tokens) {
  4. Stack<Integer> intStack = new Stack<Integer>();
  5. for(int i = 0;i<tokens.length;i++){
  6. if(tokens[i].equals("+") ||tokens[i].equals("-")
  7. ||tokens[i].equals("*") || tokens[i].equals("/")){
  8. int b = intStack.pop();
  9. int a = intStack.pop();
  10. intStack.push(cal(tokens[i],a,b));
  11. }else{
  12. intStack.push(Integer.parseInt(tokens[i]));
  13. }
  14. }
  15. return intStack.pop();
  16. }
  17. public int cal(String s,int a,int b){
  18. if(s.equals("+")) return a+b;
  19. else if(s.equals("-")) return a-b;
  20. else if(s.equals("*")) return a*b;
  21. else{
  22. return a/b;
  23. }
  24. }
  25. }

发表评论

表情:
评论列表 (有 0 条评论,232人围观)

还没有评论,来说两句吧...

相关阅读