Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes InterviewBytes/Solution.java Secret
Created Jun 6, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.