Skip to content

Commit 01bcab3

Browse files
authoredNov 5, 2024··
feat: add swift implementation to lcp problem: No.02 (#3719)
1 parent 8c233d3 commit 01bcab3

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
 

‎lcp/LCP 02. 分式化简/README.md

+30
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,36 @@ var fraction = function (cont) {
195195
};
196196
```
197197

198+
#### Swift
199+
200+
```swift
201+
class Solution {
202+
private var cont: [Int] = []
203+
204+
func fraction(_ cont: [Int]) -> [Int] {
205+
self.cont = cont
206+
return dfs(0)
207+
}
208+
209+
private func dfs(_ i: Int) -> [Int] {
210+
if i == cont.count - 1 {
211+
return [cont[i], 1]
212+
}
213+
let next = dfs(i + 1)
214+
let a = next[0]
215+
let b = next[1]
216+
let x = a * cont[i] + b
217+
let y = a
218+
let g = gcd(x, y)
219+
return [x / g, y / g]
220+
}
221+
222+
private func gcd(_ a: Int, _ b: Int) -> Int {
223+
return b == 0 ? a : gcd(b, a % b)
224+
}
225+
}
226+
```
227+
198228
<!-- tabs:end -->
199229

200230
<!-- solution:end -->
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
private var cont: [Int] = []
3+
4+
func fraction(_ cont: [Int]) -> [Int] {
5+
self.cont = cont
6+
return dfs(0)
7+
}
8+
9+
private func dfs(_ i: Int) -> [Int] {
10+
if i == cont.count - 1 {
11+
return [cont[i], 1]
12+
}
13+
let next = dfs(i + 1)
14+
let a = next[0]
15+
let b = next[1]
16+
let x = a * cont[i] + b
17+
let y = a
18+
let g = gcd(x, y)
19+
return [x / g, y / g]
20+
}
21+
22+
private func gcd(_ a: Int, _ b: Int) -> Int {
23+
return b == 0 ? a : gcd(b, a % b)
24+
}
25+
}

0 commit comments

Comments
 (0)
Please sign in to comment.