mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2024-12-27 04:46:17 +00:00
添加 Swift 代码实现
This commit is contained in:
parent
7b55df11dc
commit
8920c2d83a
@ -200,6 +200,31 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift Code:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
class Solution {
|
||||||
|
func countDigitOne(_ n: Int) -> Int {
|
||||||
|
var high = n, low = 0, cur = 0, count = 0, num = 1
|
||||||
|
while high != 0 || cur != 0 {
|
||||||
|
cur = high % 10
|
||||||
|
high /= 10
|
||||||
|
//这里我们可以提出 high * num 因为我们发现无论为几,都含有它
|
||||||
|
if cur == 0 {
|
||||||
|
count += high * num
|
||||||
|
} else if cur == 1 {
|
||||||
|
count += high * num + 1 + low
|
||||||
|
} else {
|
||||||
|
count += (high + 1) * num
|
||||||
|
}
|
||||||
|
low = cur * num + low
|
||||||
|
num *= 10
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
时间复杂度 : O(logn) 空间复杂度 O(1)
|
时间复杂度 : O(logn) 空间复杂度 O(1)
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user