★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-wvvqrlxu-me.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2
, you need to change it to the format of fraction that has denominator 1
. So in this case, 2
should be converted to 2/1
.git
Example 1:github
Input:"-1/2+1/2" Output: "0/1"
Example 2:express
Input:"-1/2+1/2+1/3" Output: "1/3"
Example 3:微信
Input:"1/3-1/2" Output: "-1/6"
Example 4:this
Input:"5/3+1/3" Output: "2/1"
Note:spa
'0'
to '9'
, '/'
, '+'
and '-'
. So does the output.±numerator/denominator
. If the first input fraction or the output is positive, then '+'
will be omitted.给定一个表示分数加减运算表达式的字符串,你须要返回一个字符串形式的计算结果。 这个结果应该是不可约分的分数,即最简分数。 若是最终结果是一个整数,例如 2
,你须要将它转换成分数形式,其分母为 1
。因此在上述例子中, 2
应该被转换为 2/1
。code
示例 1:orm
输入:"-1/2+1/2" 输出: "0/1"
示例 2:htm
输入:"-1/2+1/2+1/3" 输出: "1/3"
示例 3:
输入:"1/3-1/2" 输出: "-1/6"
示例 4:
输入:"5/3+1/3" 输出: "2/1"
说明:
'0'
到 '9'
的数字,以及 '/'
, '+'
和 '-'
。 ±分子/分母
。若是输入的第一个分数或者输出的分数是正数,则 '+'
会被省略掉。1 class Solution { 2 func fractionAddition(_ expression: String) -> String { 3 var n = 0 4 var d = 1 5 var s = Array(expression) 6 if s[0] != "-" { 7 s.insert("+", at: 0) 8 } 9 var p = 0 10 while p < s.count { 11 var p1 = p + 1 12 while s[p1] != "/" { 13 p1 += 1 14 } 15 var p2 = p1 + 1 16 while p2 < s.count && s[p2] != "+" && s[p2] != "-" { 17 p2 += 1 18 } 19 20 let nn = Int(String(s[p+1..<p1]))! 21 let dd = Int(String(s[p1+1..<p2]))! 22 let g = gcd(d, dd) 23 24 n = n * dd / g + (s[p] == "-" ? -1 : 1) * nn * d / g 25 d *= dd / g 26 p = p2 27 } 28 29 let g = gcd(abs(n), d) 30 return String(n / g) + "/" + String(d / g) 31 } 32 33 func gcd(_ a: Int, _ b: Int) -> Int { 34 return (b == 0) ? a: gcd(b, a % b) 35 } 36 }