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
一刷
用stack來解罗丰。碰到標點符號汤踏,連續(xù)彈出兩個并進行運算并壓棧,否則壓棧千扔。
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
int a, b;
for(String s : tokens){
if(s.equals("+")) stack.push(stack.pop() + stack.pop());
else if(s.equals("/")){
b = stack.pop();
a = stack.pop();
stack.push(a/b);
}
else if(s.equals("*")) stack.push(stack.pop() * stack.pop());
else if(s.equals("-")){
b = stack.pop();
a = stack.pop();
stack.push(a-b);
}
else stack.push(Integer.parseInt(s));
}
return stack.pop();
}
}
google原題此虑,階乘怎么處理