Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - 150. Evaluate Reverse Polish Notation
- struct StackElements {
- var array = [String]()
- func getTop() -> String? {
- array.last
- }
- mutating func addTop(value: Int) {
- array.append(String(value))
- }
- mutating func removeTop() -> Int {
- Int(array.removeLast())!
- }
- }
- func evalRPN(_ tokens: [String]) -> Int {
- let tokens = tokens.map{String($0)}
- var stack = StackElements()
- for token in tokens {
- // При операциях +, * мы не учитываем порядок как берем элемент из стека. Для -, / это важно
- if token == "+" {
- stack.addTop(value: stack.removeTop() + stack.removeTop())
- } else if token == "-" {
- // firstValue - вычитаемое
- let firstValue = stack.removeTop()
- let secondValue = stack.removeTop()
- stack.addTop(value: secondValue - firstValue)
- } else if token == "*" {
- stack.addTop(value: stack.removeTop() * stack.removeTop())
- } else if token == "/" {
- // firstValue - второе делимое
- let firstValue = stack.removeTop()
- let secondValue = stack.removeTop()
- stack.addTop(value: secondValue / firstValue)
- } else {
- stack.addTop(value: Int(token)!)
- }
- }
- return Int(stack.getTop()!)!
- }
- let tokens = ["4","13","5","/","+"]
- evalRPN(tokens)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement