Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Evaluate Reverse Polish Notation
class Solution {
func evalRPN(_ tokens: [String]) -> Int {
var stack = [Int]()
var operators = "+-/*"
for token in tokens {
if operators.contains(token) {
var result = 0
let second = stack.popLast()!
let first = stack.popLast()!
switch token {
case "+":
result = first + second
case "-":
result = first - second
case "*":
result = first * second
default:
result = first/second
}
stack.append(result)
}
else if let value = Int(token){
stack.append(value)
}
}
return stack[0]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment