Evaluate postfix expression
Java
Hard
5 views
Problem Description
Task: evaluate postfix expression given as int tokens and ops codes. Use stack.
Output Format
Return value
Constraints
ops: -1 add, -2 sub, -3 mul, -4 div.
Official Solution
static int evalPostfix(int[] t){java.util.ArrayDeque<Integer> st=new java.util.ArrayDeque<>();for(int x:t){if(x>=0){st.push(x);}else{int b=st.pop(),a=st.pop();int r=0; if(x==-1) r=a+b; else if(x==-2) r=a-b; else if(x==-3) r=a*b; else r=a/b; st.push(r);} }return st.pop();}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!