How to execute multiplications and/or divisions in the right order?

后端 未结 5 1711
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 21:11

I am doing a simple calculator, but when performing the multiplication and division, my code doesn\'t make them a priority over plus and minus. When doing -> 2 + 2 * 4, res

5条回答
  •  滥情空心
    2020-12-21 21:36

    If you don't care speed, as it's running by a computer and you may use the machine way to handle it. Just pick one feasible calculate to do it and then repeat until every one is calculated.

    Just for fun here. I use some stupid variable and function names.

      func evaluate(_ values: [String]) -> String{
            switch values[1] {
            case "+": return String(Int(values[0])! + Int(values[2])!)
            case "-": return String(Int(values[0])! - Int(values[2])!)
            case "×": return String(Int(values[0])! * Int(values[2])!)
            case "÷": return String(Int(values[0])! / Int(values[2])!)
            default: break;
            }
            return "";
        }
    
        func oneTime(_  string: inout String, _ strings: [String]) throws{
        if let first = try NSRegularExpression(pattern:  "(\\d+)\\s*(\(strings.map{"\\\($0)"}.joined(separator: "|")))\\s*(\\d+)", options: []).firstMatch(in: string , options: [], range: NSMakeRange(0, string.count)) {
        let tempResult = evaluate((1...3).map{ (string as NSString).substring(with: first.range(at: $0))})
           string.replaceSubrange(  Range(first.range(at: 0), in: string)!  , with: tempResult)
            }
        }
    
        func recursive(_ string: inout String, _ strings: [String]) throws{
            var count : Int!
            repeat{ count = string.count ; try oneTime(&string, strings)
            } while (count != string.count)
        }
    
        func final(_ string: inout String, _ strings: [[String]])  throws -> String{
           return try strings.reduce(into: string) { (result, signs) in
                try recursive(&string, signs)
            }}
    
        var string = "17 - 23 + 10 + 7 ÷ 7"
        try final(&string, [["×","÷"],["+","-"]])
        print("result:" + string)
    

提交回复
热议问题