添加 Swift 代码实现

pull/34/head
frank-tian 2021-07-19 23:02:05 +08:00
parent 7b55df11dc
commit 8920c2d83a
1 changed files with 25 additions and 0 deletions

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)