Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 6, 2017 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/cf21e6a9ff3541b52693c16eaa96aa11 to your computer and use it in GitHub Desktop.
Save InterviewBytes/cf21e6a9ff3541b52693c16eaa96aa11 to your computer and use it in GitHub Desktop.
Evaluate Reverse Polish Notation
package com.interviewbytes.rpn;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;
public class Solution {
private static final Set<String> OPERATORS = new HashSet<>();
static {
OPERATORS.add("+");
OPERATORS.add("-");
OPERATORS.add("*");
OPERATORS.add("/");
}
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for (String token : tokens) {
if (OPERATORS.contains(token)) {
int a = stack.pop();
int b = stack.pop();
switch (token) {
case "+":
stack.push(a + b);
break;
case "-":
stack.push(b - a);
break;
case "*":
stack.push(a * b);
break;
case "/":
stack.push(b / a);
break;
default:
break;
}
} else {
stack.push(Integer.valueOf(token));
}
}
return stack.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment