Skip to content

Commit eb8ad32

Browse files
authored
feat: add swift implementation to lcof problem: No.43 (doocs#2924)
1 parent 83a941f commit eb8ad32

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

lcof/面试题43. 1~n整数中1出现的次数/README.md

+38
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,44 @@ public class Solution {
262262
}
263263
```
264264

265+
#### Swift
266+
267+
```swift
268+
class Solution {
269+
private var digits = [Int](repeating: 0, count: 12)
270+
private var memo = [[Int?]](repeating: [Int?](repeating: nil, count: 12), count: 12)
271+
272+
func countDigitOne(_ n: Int) -> Int {
273+
var n = n
274+
var i = 0
275+
while n > 0 {
276+
digits[i] = n % 10
277+
n /= 10
278+
i += 1
279+
}
280+
return dfs(i - 1, 0, true)
281+
}
282+
283+
private func dfs(_ pos: Int, _ count: Int, _ limit: Bool) -> Int {
284+
if pos < 0 {
285+
return count
286+
}
287+
if !limit && memo[pos][count] != nil {
288+
return memo[pos][count]!
289+
}
290+
let upperLimit = limit ? digits[pos] : 9
291+
var ans = 0
292+
for i in 0...upperLimit {
293+
ans += dfs(pos - 1, count + (i == 1 ? 1 : 0), limit && i == upperLimit)
294+
}
295+
if !limit {
296+
memo[pos][count] = ans
297+
}
298+
return ans
299+
}
300+
}
301+
```
302+
265303
<!-- tabs:end -->
266304

267305
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
private var digits = [Int](repeating: 0, count: 12)
3+
private var memo = [[Int?]](repeating: [Int?](repeating: nil, count: 12), count: 12)
4+
5+
func countDigitOne(_ n: Int) -> Int {
6+
var n = n
7+
var i = 0
8+
while n > 0 {
9+
digits[i] = n % 10
10+
n /= 10
11+
i += 1
12+
}
13+
return dfs(i - 1, 0, true)
14+
}
15+
16+
private func dfs(_ pos: Int, _ count: Int, _ limit: Bool) -> Int {
17+
if pos < 0 {
18+
return count
19+
}
20+
if !limit && memo[pos][count] != nil {
21+
return memo[pos][count]!
22+
}
23+
let upperLimit = limit ? digits[pos] : 9
24+
var ans = 0
25+
for i in 0...upperLimit {
26+
ans += dfs(pos - 1, count + (i == 1 ? 1 : 0), limit && i == upperLimit)
27+
}
28+
if !limit {
29+
memo[pos][count] = ans
30+
}
31+
return ans
32+
}
33+
}

0 commit comments

Comments
 (0)