leetcode--Evaluate Reverse Polish Notation

来源:互联网 发布:如何注销淘宝安全中心 编辑:程序博客网 时间:2024/06/06 07:24

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
[java] view plain copy
  1. public class Solution {  
  2.     public int evalRPN(String[] tokens) {  
  3.         Stack<String> stack = new Stack<String>();        
  4.         int num1 = 0;  
  5.         int num2 = 0;  
  6.         for(int i=0;i<tokens.length;i++){  
  7.             switch (tokens[i]) {  
  8.             case "+":  
  9.                 num1 = Integer.valueOf(stack.pop());  
  10.                 num2 = Integer.valueOf(stack.pop());  
  11.                 stack.add((num2+num1)+"");  
  12.                 break;  
  13.             case "-":  
  14.                 num1 = Integer.valueOf(stack.pop());  
  15.                 num2 = Integer.valueOf(stack.pop());  
  16.                 stack.add((num2-num1)+"");  
  17.                 break;  
  18.             case "*":  
  19.                 num1 = Integer.valueOf(stack.pop());  
  20.                 num2 = Integer.valueOf(stack.pop());  
  21.                 stack.add((num2*num1)+"");  
  22.                 break;  
  23.             case "/":  
  24.                 num1 = Integer.valueOf(stack.pop());  
  25.                 num2 = Integer.valueOf(stack.pop());  
  26.                 stack.add((num2/num1)+"");  
  27.                 break;  
  28.             default:  
  29.                 stack.add(tokens[i]);  
  30.                 break;  
  31.             }  
  32.         }  
  33.         return Integer.valueOf(stack.pop());  
  34.     }  
  35. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46566389

原创粉丝点击