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

Evaluate Reverse Polish Notation

2016-07-17 20:10 477 查看
Evaluate the value of an arithmetic expression in Reverse Polish Notation.Valid operators are
+
,
-
,
*
,
/
. Each operand may be an integer or another expression.Example
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

Analysis:
Use a stack to save the numbers, once an operator is found, pop two numbers from stack, and push the result back to stack. Note: make sure the order of the operands.
public class Solution {
/**
* @param tokens The Reverse Polish Notation
* @return the value
*/
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) return 0;
Stack<Integer> stack = new Stack<Integer>();

for (int i = 0; i < tokens.length; i++) {
if (!(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/"))) {
stack.push(Integer.parseInt(tokens[i]));
} else {
if (stack.size() < 2) return 0;
int value1 = stack.pop();
int value2 = stack.pop();
if (tokens[i].equals("+")) {
stack.push(value1 + value2);
} else if (tokens[i].equals("-")) {
stack.push(value2 - value1);
} else if (tokens[i].equals("*")) {
stack.push(value1 * value2);
} else {
if (value1 == 0) {
return Integer.MAX_VALUE;
}
stack.push(value2 / value1);
}
}
}
return stack.pop();
}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: