Skip to content

Commit 8920c2d

Browse files
committed
添加 Swift 代码实现
1 parent 7b55df1 commit 8920c2d

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

animation-simulation/剑指offer/1的个数.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,31 @@ class Solution {
200200
}
201201
```
202202

203+
Swift Code:
204+
205+
```swift
206+
class Solution {
207+
func countDigitOne(_ n: Int) -> Int {
208+
var high = n, low = 0, cur = 0, count = 0, num = 1
209+
while high != 0 || cur != 0 {
210+
cur = high % 10
211+
high /= 10
212+
//这里我们可以提出 high * num 因为我们发现无论为几,都含有它
213+
if cur == 0 {
214+
count += high * num
215+
} else if cur == 1 {
216+
count += high * num + 1 + low
217+
} else {
218+
count += (high + 1) * num
219+
}
220+
low = cur * num + low
221+
num *= 10
222+
}
223+
return count
224+
}
225+
}
226+
```
227+
203228
时间复杂度 : O(logn) 空间复杂度 O(1)
204229

205230

0 commit comments

Comments
 (0)