forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChaedie.py
More file actions
59 lines (47 loc) ยท 1.25 KB
/
Chaedie.py
File metadata and controls
59 lines (47 loc) ยท 1.25 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
50
51
52
53
54
55
56
57
58
59
"""
Solution:
1) bin() ๋ฉ์๋๋ก binary ๋ง๋ค์ด์ฃผ๊ณ
2) 1 ์ ๊ฐฏ์๋ฅผ ์ธ์ด์ค๋ค.
Time: O(n^2)
Space: O(1)
"""
class Solution:
def countBits(self, n: int) -> List[int]:
result = [0 for i in range(n + 1)]
for i in range(n+1):
b = bin(i)
count = 0
for char in b:
if char == '1':
count += 1
result[i] = count
return result
"""
Solution:
1) 2๋ก ๋๋ ๋๋จธ์ง๊ฐ 1bit ์ด๋ผ๋ ์ฑ์ง์ ์ด์ฉํด์ count
Time: O(n logn)
Space: O(1)
"""
class Solution:
def countBits(self, n: int) -> List[int]:
def count(num):
count = 0
while num > 0:
count += num % 2
num = num // 2
return count
return [count(i) for i in range(n+1)]
"""
Solution:
1) LSB ๊ฐ 0 1 0 1 ๋ฐ๋ณต๋๋ฏ๋ก num % 2 ๋ฅผ ์ฌ์ฉํ๋ค.
2) ๋๋จธ์ง ๋น์ LSB๋ฅผ ์ ์ธํ ๊ฐ์ด๋ฏ๋ก num // 2 ๋ฅผ ์ฌ์ฉํ๋ค.
Time: O(n)
Space: O(1)
"""
class Solution:
def countBits(self, n: int) -> List[int]:
dp = [0 for i in range(n+1)]
for i in range(1, n+1):
LSB = i % 2
dp[i] = dp[i // 2] + LSB
return dp