您的位置:首页 > 编程语言 > Lua

150. Evaluate Reverse Polish Notation (M)

2017-01-28 22:45 381 查看
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


Subscribe to see which companies asked this question
My naive Solution:
public class Solution {
public int evalRPN(String[] tokens) {
int re=0;
CharSequence operator="+-*/";
Stack<Integer> data=new Stack<Integer>();
for(String i:tokens){
if(i.equals("+")||i.equals("-")||i.equals("*")||i.equals("/")){
int n2=data.pop();
int n1=data.pop();
int temp=0;
char oper=i.charAt(0);
switch(oper){
case('+'):
temp=n1+n2;
break;
case('-'):
temp=n1-n2;
break;
case('*'):
temp=n1*n2;
break;
case('/'):
temp=n1/n2;
break;
default:
break;
}
data.push(temp);
}
else
data.push(Integer.valueOf(i));
}
return data.pop();
}
}

Cleaner:
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> data=new Stack<Integer>();
for(String i:tokens){
switch(i){
case("+"):
data.push(data.pop()+data.pop());
break;
case("-"):
data.push(-data.pop()+data.pop());
break;
case("*"):
data.push(data.pop()*data.pop());
break;
case("/"):
int n2=data.pop();
int n1=data.pop();
data.push(n1/n2);
break;
default:
data.push(Integer.valueOf(i));
break;
}
}
return data.pop();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: