给定一个表示分数加减运算表达式的字符串,你需要返回一个字符串形式的计算结果。 这个结果应该是不可约分的分数,即最简分数。 如果最终结果是一个整数,例如 2
,你需要将它转换成分数形式,其分母为 1
。所以在上述例子中, 2
应该被转换为 2/1
。
解法:分子 = a分子b分母 + a分母b分子 ,分母 = a分母 * b分母
然后约分,约分需要用到欧几里得算法求最大公约数
func gcd(_ a:Int ,_ b:Int) -> Int {
var inA = a,inB = b
if a > b {
inA = b
inB = a
}
while inA != 0 {
let temp = inA
inA = inB % inA
inB = temp
}
return abs(inB)
}
func fractionAddition(_ expression: String) -> String {
var n: Int = 0,d: Int = 1
var startIndex = expression.startIndex
while startIndex < expression.endIndex {
var leftIndex = startIndex
repeat {
leftIndex = expression.index(after: leftIndex)
}while (expression[leftIndex] != "/");
let range = expression[startIndex..<leftIndex]
let fenzi:Int = Int(String(range))!
var rightIndex = expression.index(after: leftIndex)
while (rightIndex < expression.endIndex && expression[rightIndex] != "+" && expression[rightIndex] != "-") {
rightIndex = expression.index(after: rightIndex)
}
let range2 = expression[expression.index(after: leftIndex)..<rightIndex]
let fenmu:Int = Int(String(range2))!
n = n*fenmu + fenzi*d
d = d * fenmu
let gcd = self.gcd(n, d)
n = n / gcd
d = d / gcd
startIndex = rightIndex
}
return "\(n)/\(d)"
}