Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: A UIKit based Playground for presenting user interface
- import UIKit
- import PlaygroundSupport
- import Foundation
- func reversedPolPost(_ input: String){
- var resultArray = [Character]()
- var sequencePriority = false
- var gap = 0 // gap for opertion prior
- var existOutOfSequencePriorityLowOperation = false
- var array = Array(input)
- for i in 0..<array.count {
- if array[i] == "+" || array[i] == "-" {
- if sequencePriority{
- resultArray.append(array[i])
- let temp = resultArray[resultArray.count-1]
- resultArray[resultArray.count-1] = resultArray[resultArray.count-2]
- resultArray[resultArray.count-2] = temp
- } else {
- resultArray.insert(array[i], at: 0)
- existOutOfSequencePriorityLowOperation = true
- gap += 1
- }
- }
- if array[i] == "*" || array[i] == "/" {
- if sequencePriority{
- resultArray.append(array[i])
- let temp = resultArray[resultArray.count-1]
- resultArray[resultArray.count-1] = resultArray[resultArray.count-2]
- resultArray[resultArray.count-2] = temp
- } else {
- existOutOfSequencePriorityLowOperation ? resultArray.insert(array[i], at: gap) : resultArray.insert(array[i], at: 0)
- }
- }
- if array[i] == "(" {
- sequencePriority = true
- }
- if array[i] == ")" {
- sequencePriority = false
- }
- if array[i].isNumber || array[i] == "."{ //number
- var gap = i
- while i < array.count { //(array[i].isNumber || array[i] == ".") &&
- if let _ = Int(String(array[gap])) {
- resultArray.append(array[gap])
- array[gap] = "n"
- gap += 1
- } else {
- if (array[gap] == "+" || array[gap] == "-" || array[gap] == "/" || array[gap] == "*") {
- resultArray.insert(array[gap], at: gap-(gap-i))
- array[gap] = "n"
- break
- }
- if (array[gap] == ".") {
- resultArray.append(array[gap])
- array[gap] = "n"
- gap += 1
- }
- }
- }
- resultArray.append(" ")
- }
- }
- print(String(resultArray))
- }
- reversedPolPost("5+(874+1)*86+9")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement