该算法不包含括号运算!
主要思路是利用递归算法
1、先把减法变成加法,把除法变成乘法
2、截取优先级低的算式,将优先级高的算式递归调用本身算出结果
直接上代码
func calcuterResult(input: String) -> Double {
let newStr = input.replacingOccurrences(of: "-", with: "+-") //减法变加法
.replacingOccurrences(of: "/", with: "*1/") //除法变乘法
return calcuter(input: newStr)
}
func calcuter(input: String) -> Double {
if input.contains("+") { // 加法运算
var result = 0.0
let values = input.components(separatedBy: "+")
for value in values {
guard !value.isEmpty else { continue }
if let num = Double(value) {
result = result + num
} else {
result = result + calcuter(input: value)
}
}
return result
} else { // 乘法结果
var result = 1.0
let values = input.components(separatedBy: "*")
for value in values {
guard !value.isEmpty else { continue }
if let num = Double(value) {
result = result * num
} else {
// "1/2" ,"1/5"
let coms = value.components(separatedBy: "/")
if let num = coms.last {
result = result * 1 / (Double(num) ?? 1)
}
}
}
return result
}
}
网友评论