Skip to content

Commit

Permalink
[Stack] Refactor solution to Evaluate Reverse Polish Notation
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu authored Sep 29, 2019
1 parent a96c958 commit 6088f7b
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions Stack/EvaluateReversePolishNotation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,39 @@
*/

class EvaluateReversePolishNotation {
func evalRPN(_ tokens: [String]) -> Int {
var stack = [Int]()
var stack = [Int]()

for token in tokens {
if let num = Int(token) {
stack.append(num)
} else {
let post = stack.removeLast()
let prev = stack.removeLast()
guard let postNum = stack.popLast(), let prevNum = stack.popLast() else {
fatalError("Invalid Input")
}

stack.append(operate(prev, post, token))
stack.append(operate(token, prevNum, postNum))
}
}

return stack.first ?? 0
if let last = stack.last {
return last
} else {
fatalError("Invalid Input")
}
}

fileprivate func _operate(_ prev: Int, _ post: Int, _ token: String) -> Int{
private func operate(_ token: String, _ prevNum: Int, _ postNum: Int) -> Int {
switch token {
case "+":
return prev + post
return prevNum + postNum
case "-":
return prev - post
return prevNum - postNum
case "*":
return prev * post
return prevNum * postNum
case "/":
return prevNum / postNum
default:
return prev / post
}
fatalError("Invalid Input")
}
}
}
}

0 comments on commit 6088f7b

Please sign in to comment.