https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

(图片来源https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
)
日期 | 是否一次通过 | comment |
---|---|---|
2020-03-18 | 0 |
递归
public int evalRPN(String[] tokens) {
int res = 0;
if(tokens == null || tokens.length <= 0) {
return res;
}
Stack<Integer> stk = new Stack<>();
int a = 0, b = 0;
for(String s : tokens) {
if(s.equals("+")) {
a = stk.pop();
b = stk.pop();
stk.push(b+a);
} else if(s.equals("-")) {
a = stk.pop();
b = stk.pop();
stk.push(b-a);
} else if(s.equals("*")) {
a = stk.pop();
b = stk.pop();
stk.push(b*a);
} else if(s.equals("/")) {
a = stk.pop();
b = stk.pop();
stk.push(b/a);
} else {
stk.push(Integer.parseInt(s));
}
}
return stk.pop();
}
网友评论