添加 Swift 代码实现

This commit is contained in:
frank-tian 2021-07-19 23:02:05 +08:00
parent 7b55df11dc
commit 8920c2d83a

View File

@ -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)