求解一个给定的方程,将x
以字符串"x=#value"的形式返回。该方程仅包含'+',' - '操作,变量 x
和其对应系数。
如果方程没有解,请返回“No solution”。
如果方程有无限解,则返回“Infinite solutions”。
如果方程中只有一个解,要保证返回值 x
是一个整数。
解析字符串,按照普通的解方程手法进行
let index:String.Index = equation.index(of: "=")!
let leftStr = equation[..<index]
let rightStr = equation[equation.index(after: index)...]
var leftNum: Int = 0
var leftX: Int = 0
var tempStr: String = ""
for aChar in leftStr {
if aChar == "x" {
if tempStr.isEmpty {
leftX += 1
}else {
if tempStr.last == "+" || tempStr.last == "-" {
tempStr += "1"
}
leftX += Int(tempStr)!
tempStr = ""
}
}else if aChar == "+" || aChar == "-" {
if !tempStr.isEmpty {
leftNum += Int(tempStr)!
}
tempStr = String(aChar)
}else {
tempStr += String(aChar)
}
}
if !tempStr.isEmpty {
leftNum += Int(tempStr)!
tempStr = ""
}
var rightNum: Int = 0
var rightX: Int = 0
for aChar in rightStr {
if aChar == "x" {
if tempStr.isEmpty {
rightX += 1
}else {
if tempStr.last == "+" || tempStr.last == "-" {
tempStr += "1"
}
rightX += Int(tempStr)!
tempStr = ""
}
}else if aChar == "+" || aChar == "-" {
if !tempStr.isEmpty {
rightNum += Int(tempStr)!
}
tempStr = String(aChar)
}else {
tempStr += String(aChar)
}
}
if !tempStr.isEmpty {
rightNum += Int(tempStr)!
}
leftX = leftX - rightX
rightNum = rightNum - leftNum
var rstStr = ""
if leftX == 0 {
if rightNum == 0 {
rstStr = "Infinite solutions"
}else {
rstStr = "No solution"
}
}else {
let rstNum = Double(rightNum) / Double(leftX)
var rstInt = Int(rstNum)
if rstNum < Double(rstInt) {
rstInt -= 1
}
rstStr = "x=\(rstInt)"
}
return rstStr