diff --git a/animation-simulation/剑指offer/1的个数.md b/animation-simulation/剑指offer/1的个数.md index 79c2f31..d3942c2 100644 --- a/animation-simulation/剑指offer/1的个数.md +++ b/animation-simulation/剑指offer/1的个数.md @@ -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)