Evaluate Reverse Polish Notation
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)) -> 6Java代码:
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
if (tokens.length == 0)
return 0;
for (int i = 0; i < tokens.length; i++) {
if (isNum(tokens[i])) {
stack.push(Integer.parseInt(tokens[i]));
} else {
Integer n2 = stack.pop();
Integer n1 = stack.pop();
Integer result;
if (tokens[i].equals("+")) {
result = n1 + n2;
stack.push(result);
} else if (tokens[i].equals("-")) {
result = n1 - n2;
stack.push(result);
} else if (tokens[i].equals("*")) {
result = n1 * n2;
stack.push(result);
} else if (tokens[i].equals("/")) {
result = n1 / n2;
stack.push(result);
}
}
}
return stack.pop();
}
public boolean isNum(String s) {
try {
Integer.parseInt(s);
return true;
} catch (Exception e) {
return false;
}
}
}
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
if (tokens.length == 0)
return 0;
for (int i = 0; i < tokens.length; i++) {
if (isNum(tokens[i])) {
stack.push(Integer.parseInt(tokens[i]));
} else {
Integer n2 = stack.pop();
Integer n1 = stack.pop();
Integer result;
if (tokens[i].equals("+")) {
result = n1 + n2;
stack.push(result);
} else if (tokens[i].equals("-")) {
result = n1 - n2;
stack.push(result);
} else if (tokens[i].equals("*")) {
result = n1 * n2;
stack.push(result);
} else if (tokens[i].equals("/")) {
result = n1 / n2;
stack.push(result);
}
}
}
return stack.pop();
}
public boolean isNum(String s) {
try {
Integer.parseInt(s);
return true;
} catch (Exception e) {
return false;
}
}
}