题目分析
题目链接
这道题目是要用栈来模拟四则运算。
代码
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
// Stack
// push pop peek empty search
if(tokens == null) {
return 0;
}
Stack<Integer> s = new Stack<>();
for(String token : tokens) {
if(token.equals("+")) {
s.push(s.pop() + s.pop());
} else if(token.equals("-")) {
int operandRight = s.pop();
int operandLeft = s.pop();
s.push(operandLeft - operandRight);
} else if(token.equals("*")) {
s.push(s.pop() * s.pop());
} else if(token.equals("/")) {
int operandRight = s.pop();
int operandLeft = s.pop();
s.push(operandLeft / operandRight);
} else {
s.push(Integer.valueOf(token));
}
}
return s.pop();
}
}
网友评论