# leetcode

Datetime:2016-08-23 01:20:52         Topic: LeetCode          Share        Original >>

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

package com.cn.cya.evaluatereversepolishnotation;
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {

Stack<Integer> stack=new Stack<Integer>();
if(tokens==null||tokens.equals(""))return 0;
for (int i = 0; i < tokens.length; i++) {
if(tokens[i].equals("+")){
int a=stack.pop();
int b=stack.pop();
stack.push(b+a);
}else if(tokens[i].equals("-")){
int a=stack.pop();
int b=stack.pop();
stack.push(b-a);
}else if(tokens[i].equals("*")){
int a=stack.pop();
int b=stack.pop();
stack.push(a*b);
}else if(tokens[i].equals("/")){
int a=stack.pop();
if(a==0)return 0;
int b=stack.pop();
stack.push(b/a);
}else {
int a=Integer.parseInt(tokens[i]);
stack.push(a);
}
}
return stack.pop();

}
}