求解一個給定的方程倒戏,將x
以字符串"x=#value"的形式返回。該方程僅包含'+'瞭吃,' - '操作碌嘀,變量 x
和其對應(yīng)系數(shù)。
如果方程沒有解歪架,請返回“No solution”股冗。
如果方程有無限解,則返回“Infinite solutions”牡拇。
如果方程中只有一個解,要保證返回值 x
是一個整數(shù)穆律。
解析字符串惠呼,按照普通的解方程手法進(jìn)行
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