https://leetcode.com/problems/evaluate-reverse-polish-notation/description/
코드설명
스택(Stack) + 후위표기법(polish-notation)을 활용합니다.
후위표기법대로, 연산자를 만날경우 스택의 가장 최상단 숫자 2개를 pop한뒤, 연산을 합니다.
코드
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> st = new Stack<>();
for(String v : tokens){
if(v.equals("+")){
int num1 = st.pop();
int num2 = st.pop();
st.push(num1 + num2);
}else if(v.equals("-")){
int num1 = st.pop();
int num2 = st.pop();
st.push(num2 - num1);
}else if(v.equals("*")){
int num1 = st.pop();
int num2 = st.pop();
st.push(num1 * num2);
}else if(v.equals("/")){
int num1 = st.pop();
int num2 = st.pop();
st.push(num2 / num1);
}else {
st.push(Integer.parseInt(v));
}
}
// System.out.println(st.pop());
return st.pop();
}
}