feat: add swift implementation to lcp problem: No.02 (#3719)

This commit is contained in:
Lanre Adedara 2024-11-05 10:05:41 +01:00 committed by GitHub
parent 8c233d3e21
commit 01bcab3f09
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 55 additions and 0 deletions

View File

@ -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 -->

View File

@ -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)
}
}