![[Swift]LeetCode592. 分数加减运算 | Fraction Addition and Subtraction,第1张 [Swift]LeetCode592. 分数加减运算 | Fraction Addition and Subtraction,第1张](/aiimages/%5BSwift%5DLeetCode592.+%E5%88%86%E6%95%B0%E5%8A%A0%E5%87%8F%E8%BF%90%E7%AE%97+%7C+Fraction+Addition+and+Subtraction.png)
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.
Example 1:
input:"-1/2+1/2"Output: "0/1"
Example 2:
input:"-1/2+1/2+1/3"Output: "1/3"
Example 3:
input:"1/3-1/2"Output: "-1/6"
Example 4:
input:"5/3+1/3"Output: "2/1"
Note:
The input string only contains‘0‘ to ‘9‘, ‘/‘, ‘+‘ and ‘-‘. So does the output. Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive,then ‘+‘ will be omitted. The input only contains valID irreducible fractions,where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1,it means this fraction is actually an integer in a fraction format defined above. The number of given fractions will be in the range [1,10]. The numerator and denominator of the final result are guaranteed to be valID and in the range of 32-bit int. 给定一个表示分数加减运算表达式的字符串,你需要返回一个字符串形式的计算结果。 这个结果应该是不可约分的分数,即最简分数。 如果最终结果是一个整数,例如 2,你需要将它转换成分数形式,其分母为 1。所以在上述例子中, 2 应该被转换为 2/1。
示例 1:
输入:"-1/2+1/2"输出: "0/1"
示例 2:
输入:"-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,10]。 如果分母是1,意味着这个分数实际上是一个整数。 输入的分数个数范围是 [1,10]。 最终结果的分子与分母保证是 32 位整数范围内的有效整数。 Runtime: 8 ms Memory Usage: 19.4 MB 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 = 010 while p < s.count {11 var p1 = p + 112 while s[p1] != "/" {13 p1 += 114 }15 var p2 = p1 + 116 while p2 < s.count && s[p2] != "+" && s[p2] != "-" {17 p2 += 118 }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 / g25 d *= dd / g26 p = p227 }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 }总结
以上是内存溢出为你收集整理的[Swift]LeetCode592. 分数加减运算 | Fraction Addition and Subtraction全部内容,希望文章能够帮你解决[Swift]LeetCode592. 分数加减运算 | Fraction Addition and Subtraction所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)