Created
May 25, 2021 09:57
-
-
Save vrat28/6e8262208e92acfa501294c428d4990a to your computer and use it in GitHub Desktop.
Evaluate Reverse Polish Notation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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