Evaluate Reverse Polish Notation https://oj.leetcode.com/problems/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)) -> 6
这个题没什么好说的,用栈就可以了,注意一下两个数计算的时候谁前谁后就行了。
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<String>();
int num1 = 0;
int num2 = 0;
for(int i = 0; i < tokens.length; i++){
if (tokens[i].equals("+")){
//calcuate
num1 = Integer.parseInt(stack.pop());
num2 = Integer.parseInt(stack.pop());
stack.push(String.format("%s", num2+num1));
}else if(tokens[i].equals("-")){
num1 = Integer.parseInt(stack.pop());
num2 = Integer.parseInt(stack.pop());
stack.push(String.format("%s", num2-num1));
}else if(tokens[i].equals("*")){
num1 = Integer.parseInt(stack.pop());
num2 = Integer.parseInt(stack.pop());
stack.push(String.format("%s", num2*num1));
}else if(tokens[i].equals("/")){
num1 = Integer.parseInt(stack.pop());
num2 = Integer.parseInt(stack.pop());
stack.push(String.format("%s", num2/num1));
}else{
//push to stack
stack.push(tokens[i]);
}
}
return Integer.parseInt(stack.peek());
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。