forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhi-rachel.py
More file actions
49 lines (40 loc) ยท 1.27 KB
/
hi-rachel.py
File metadata and controls
49 lines (40 loc) ยท 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
์ ์ n์ด ์ฃผ์ด์ก์ ๋, 0๋ถํฐ n๊น์ง์ ๋ชจ๋ ์์ ๋ํด ๊ฐ ์๋ฅผ ์ด์ง์๋ก ํํํ์ ๋ 1์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์
TC: O(N log N), ๋ชจ๋ ์ ์ํ + ์ด์ง์ ๋ณํ ๊ณผ์ (log i)
SC: O(N)
"""
from typing import List
# ์ฒ์ ํ์ด
class Solution:
def countBits(self, n: int) -> List[int]:
def countOne(num):
cnt = 0
while True:
rest = num % 2
if rest == 1:
cnt += 1
num //= 2
if num <= 1:
if num == 1:
cnt += 1
break
return cnt
result = []
for i in range(0, n + 1):
result.append(countOne(i))
return result
"""
DP ํ์ด - ์๊ฐ ๋ณต์ก๋ ๊ฐ์
bits[i] = bits[i >> 1] + (i &)
i >> 1 ์ i๋ฅผ ์ค๋ฅธ์ชฝ์ผ๋ก 1๋นํธ ์ด๋ -> i๋ฅผ 2๋ก ๋๋ ๊ฐ
i & 1 ์ i์ ๋ง์ง๋ง 1๋นํธ๊ฐ 1์ธ์ง ํ์ธ, ์ง์๋ฉด 0, ํ์๋ฉด 1
i์ 1์ ๊ฐ์ = i๋ฅผ 2๋ก ๋๋ ์์ 1์ ๊ฐ์ + ๋ง์ง๋ง ๋นํธ๊ฐ 1์ธ์ง ์ฌ๋ถ
TC: O(N)
SC: O(N)
"""
class Solution:
def countBits(self, n: int) -> List[int]:
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = dp[i >> 1] + (i & 1)
return dp