Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions lcp/LCP 02. 分式化简/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,36 @@ var fraction = function (cont) {
};
```

#### Swift

```swift
class Solution {
private var cont: [Int] = []

func fraction(_ cont: [Int]) -> [Int] {
self.cont = cont
return dfs(0)
}

private func dfs(_ i: Int) -> [Int] {
if i == cont.count - 1 {
return [cont[i], 1]
}
let next = dfs(i + 1)
let a = next[0]
let b = next[1]
let x = a * cont[i] + b
let y = a
let g = gcd(x, y)
return [x / g, y / g]
}

private func gcd(_ a: Int, _ b: Int) -> Int {
return b == 0 ? a : gcd(b, a % b)
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
25 changes: 25 additions & 0 deletions lcp/LCP 02. 分式化简/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution {
private var cont: [Int] = []

func fraction(_ cont: [Int]) -> [Int] {
self.cont = cont
return dfs(0)
}

private func dfs(_ i: Int) -> [Int] {
if i == cont.count - 1 {
return [cont[i], 1]
}
let next = dfs(i + 1)
let a = next[0]
let b = next[1]
let x = a * cont[i] + b
let y = a
let g = gcd(x, y)
return [x / g, y / g]
}

private func gcd(_ a: Int, _ b: Int) -> Int {
return b == 0 ? a : gcd(b, a % b)
}
}
Loading