From 8920c2d83a56a28ed47df355698789b391e90b9a Mon Sep 17 00:00:00 2001 From: frank-tian Date: Mon, 19 Jul 2021 23:02:05 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20Swift=20=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- animation-simulation/剑指offer/1的个数.md | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) 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)