Skip to content

Commit 698f216

Browse files
authoredMay 27, 2024
feat: add swift implementation to lcof problem: No.44 (doocs#2925)
1 parent eb8ad32 commit 698f216

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
 

‎lcof/面试题44. 数字序列中某一位的数字/README.md

+31
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,37 @@ public class Solution {
166166
}
167167
```
168168

169+
#### Swift
170+
171+
```swift
172+
class Solution {
173+
func findNthDigit(_ n: Int) -> Int {
174+
var n = n
175+
var k = 1
176+
var count = 9
177+
178+
while k * count < n {
179+
n -= k * count
180+
k += 1
181+
count *= 10
182+
}
183+
184+
let num = Int(Double(10).power(Double(k - 1))) + (n - 1) / k
185+
let idx = (n - 1) % k
186+
let numString = String(num)
187+
let char = numString[numString.index(numString.startIndex, offsetBy: idx)]
188+
189+
return char.wholeNumberValue!
190+
}
191+
}
192+
193+
extension Double {
194+
func power(_ exponent: Double) -> Double {
195+
return pow(self, exponent)
196+
}
197+
}
198+
```
199+
169200
<!-- tabs:end -->
170201

171202
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
func findNthDigit(_ n: Int) -> Int {
3+
var n = n
4+
var k = 1
5+
var count = 9
6+
7+
while k * count < n {
8+
n -= k * count
9+
k += 1
10+
count *= 10
11+
}
12+
13+
let num = Int(Double(10).power(Double(k - 1))) + (n - 1) / k
14+
let idx = (n - 1) % k
15+
let numString = String(num)
16+
let char = numString[numString.index(numString.startIndex, offsetBy: idx)]
17+
18+
return char.wholeNumberValue!
19+
}
20+
}
21+
22+
extension Double {
23+
func power(_ exponent: Double) -> Double {
24+
return pow(self, exponent)
25+
}
26+
}

0 commit comments

Comments
 (0)
Please sign in to comment.