How to evaluate an expression using Reverse Polish Notation?

2026-04-01 19:592阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计257个文字,预计阅读时间需要2分钟。

How to evaluate an expression using Reverse Polish Notation?

题目:计算逆波兰表示法中算术表达式的值。有效的运算符有+、-、*、/。每个操作数可能是一个整数或另一个表达式。以下是一些示例:[2, 1, +, 3, *] -> ((2+1)*3) - 9[4, 1]

题目:

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

解答:

1 public class Solution { 2 3 private static final Set<String> OPERATORS = 4 new HashSet<>(Arrays.asList("+", "-", "*", "/")); 5 6 public int eval(int x, int y, String operator) { 7 switch(operator) { 8 case "+": 9 return x+y; 10 case "-": 11 return x-y; 12 case "*": 13 return x*y; 14 case "/": 15 return x/y; 16 } 17 } 18 19 public int evalPRN(String[] tokens) { 20 Stack<Integer> stack = new Stack<>(); 21 for(String token : tokens) { 22 if(OPERATORS.contais(token)) { 23 int y = stack.pop(); 24 int x = stack.pop(); 25 stack.push(eval(x, y, token)); 26 } else { 27 stack.push(Integer.parseInt(token)); 28 } 29 } 30 31 return stack.pop(); 32 } 33 }

How to evaluate an expression using Reverse Polish Notation?

本文共计257个文字,预计阅读时间需要2分钟。

How to evaluate an expression using Reverse Polish Notation?

题目:计算逆波兰表示法中算术表达式的值。有效的运算符有+、-、*、/。每个操作数可能是一个整数或另一个表达式。以下是一些示例:[2, 1, +, 3, *] -> ((2+1)*3) - 9[4, 1]

题目:

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

解答:

1 public class Solution { 2 3 private static final Set<String> OPERATORS = 4 new HashSet<>(Arrays.asList("+", "-", "*", "/")); 5 6 public int eval(int x, int y, String operator) { 7 switch(operator) { 8 case "+": 9 return x+y; 10 case "-": 11 return x-y; 12 case "*": 13 return x*y; 14 case "/": 15 return x/y; 16 } 17 } 18 19 public int evalPRN(String[] tokens) { 20 Stack<Integer> stack = new Stack<>(); 21 for(String token : tokens) { 22 if(OPERATORS.contais(token)) { 23 int y = stack.pop(); 24 int x = stack.pop(); 25 stack.push(eval(x, y, token)); 26 } else { 27 stack.push(Integer.parseInt(token)); 28 } 29 } 30 31 return stack.pop(); 32 } 33 }

How to evaluate an expression using Reverse Polish Notation?