Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 25, 2021 09:57
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 vrat28/6e8262208e92acfa501294c428d4990a to your computer and use it in GitHub Desktop.
Save vrat28/6e8262208e92acfa501294c428d4990a to your computer and use it in GitHub Desktop.
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