Evaluate Reverse Polish Notation
2014-05-04 18:59
295 查看
Evaluate the value of an arithmetic expression in Reverse Polish Notation.Valid operators are [code]+,
-,
*,
/. Each operand may be an integer or another expression.Some examples:
[/code]
import java.util.Scanner; import java.util.Stack; public class Solution { public static int evalRPN(String[] tokens) { String op3="+-*/"; Stack num= new Stack(); int result=0; int index=0; int op=0; int op2=0; for(int i=0;i<tokens.length;i++){ if(op3.contains(tokens[i])){ op=Integer.valueOf(num.pop().toString()); op2=Integer.valueOf(num.pop().toString()); index=op3.indexOf(tokens[i]); switch(index) { case 0:result=op2+op;num.push(result);break; case 1:result=op2-op;num.push(result);break; case 2:result=op*op2;num.push(result);break; case 3:if(op==0)return 0; result=op2/op;num.push(result);break; } }else{ num.push(tokens[i]); } } result=Integer.valueOf(num.pop().toString()); return result; } public static void main(String[] args) { String exp; String[] exp2; char[] ch=null; int result; Scanner scan=new Scanner(System.in); exp=scan.nextLine(); exp2=exp.split(" "); result=evalRPN(exp2); System.out.println(result); } }
相关文章推荐
- Algorithms—150.Evaluate Reverse Polish Notation
- leetcode Evaluate Reverse Polish Notation
- Leetcode || Evaluate Reverse Polish Notation
- java常用算法之逆波兰表达式(Evaluate Reverse Polish Notation)
- Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- evaluate-reverse-polish-notation
- LeetCode:Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- 每日AC - 后缀表达式计算结果-leetcode-evaluate-reverse-polish-notation
- LeetCode-Evaluate Reverse Polish Notation (Python)
- Evaluate Reverse Polish Notation
- 【LeetCode练习题】Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation问题及解法
- LeetCode | Evaluate Reverse Polish Notation
- LeetCode – Evaluate Reverse Polish Notation
- 【evaluate-reverse-polish-notation】
- 150. Evaluate Reverse Polish Notation
- 【leetcode】Evaluate Reverse Polish Notation