Skip to content

feat: add swift implementation to lcof problem: No.17 #2876

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 22, 2024
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
42 changes: 42 additions & 0 deletions lcof/面试题17. 打印从1到最大的n位数/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,48 @@ public class Solution {
}
```

#### Swift

```swift
class Solution {
func printNumbers(_ n: Int) -> [Int] {
let maxNumber = maxNumberForDigits(n)
return Array(1...maxNumber)
}

private func maxNumberForDigits(_ n: Int) -> Int {
var maxNumber = 1
for _ in 0..<n {
maxNumber *= 10
}
return maxNumber - 1
}

private var s = String()
private var ans = [String]()

func print(_ n: Int) -> [String] {
for i in 1...n {
dfs(0, i)
}
return ans
}

private func dfs(_ i: Int, _ j: Int) {
if i == j {
ans.append(s)
return
}
let start = i > 0 ? 0 : 1
for k in start..<10 {
s.append("\(k)")
dfs(i + 1, j)
s.removeLast()
}
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
37 changes: 37 additions & 0 deletions lcof/面试题17. 打印从1到最大的n位数/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Solution {
func printNumbers(_ n: Int) -> [Int] {
let maxNumber = maxNumberForDigits(n)
return Array(1...maxNumber)
}

private func maxNumberForDigits(_ n: Int) -> Int {
var maxNumber = 1
for _ in 0..<n {
maxNumber *= 10
}
return maxNumber - 1
}

private var s = String()
private var ans = [String]()

func print(_ n: Int) -> [String] {
for i in 1...n {
dfs(0, i)
}
return ans
}

private func dfs(_ i: Int, _ j: Int) {
if i == j {
ans.append(s)
return
}
let start = i > 0 ? 0 : 1
for k in start..<10 {
s.append("\(k)")
dfs(i + 1, j)
s.removeLast()
}
}
}
Loading