Skip to content

Commit 9d6c29c

Browse files
Merge pull request #1637 from CodingTestStudy2/최원준
[최원준] Day06
2 parents 58a98fb + 907f0c2 commit 9d6c29c

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#
2+
3+
'''
4+
1. 아이디어 :
5+
모든 숫자를 나열하면 메모리 초과. 구간별로 나눠서 계산해야한다.
6+
자릿수 마다 계산을 하고, 이때 현재 자리를 기준으로 왼쪽, 가운데, 오른쪽으로 나눈다.
7+
그 자릿수일때 등장하는 1의 갯수는 왼쪽 숫자 * 현재 자리.
8+
다만, 3가지 경우의 수가 있다. 현재 자리가:
9+
- 0인 경우: 왼쪽 * 자릿수
10+
- 1인 경우: 왼쪽 * 자릿수 + 오른쪽 + 1
11+
- 1이상인 경우: 왼쪽+1 * 자릿수
12+
13+
2. 시간복잡도 :
14+
O(9)
15+
16+
3. 자료구조/알고리즘 :
17+
-
18+
19+
'''
20+
class Solution:
21+
def countDigitOne(self, n: int) -> int:
22+
"""
23+
0-10: 123456789 = 2
24+
11-100: 10 + 2*8 + 1 = 27
25+
26+
"""
27+
ans = 0
28+
digit = 1 # 자리수 (예시: 10)
29+
30+
while digit <= n: # 자리 수 까지 카운트 (예시: 1234)
31+
high = n // (digit * 10) # 현재 자리보다 왼쪽 (12)
32+
cur = (n // digit) % 10 # 현재 자리의 숫자 (3)
33+
low = n % digit # 오른쪽 숫자 (4)
34+
35+
if cur == 0:
36+
ans += high * digit # 1이 등장하는건 10의 자리에서 나오는 1의 갯수 * 왼쪽 카운트 (예시: 1203 -> 12*10)
37+
elif cur == 1:
38+
ans += high * digit + low + 1 # 마지막 구간이 다름 (전부 1. 예시 1213)
39+
else:
40+
ans += (high + 1) * digit # 10의 자리를 지나왔기에 +1 세트 (예시 1234)
41+
42+
digit *= 10
43+
44+
return ans

0 commit comments

Comments
 (0)