forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKwonNayeon.py
More file actions
33 lines (28 loc) ยท 868 Bytes
/
KwonNayeon.py
File metadata and controls
33 lines (28 loc) ยท 868 Bytes
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
"""
Constraints:
- 0 <= n <= 10^5
Time Complexity: O(n log n)
- ์ธ๋ถ ๋ฃจํ: O(n) (0๋ถํฐ n๊น์ง ๋ฐ๋ณต)
- hammingWeight ํจ์: O(log n)
- ์ด ์๊ฐ ๋ณต์ก๋: O(n) * O(log n) = O(n log n)
Space Complexity: O(n)
- ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ๊ธฐ ์ํ ๊ธธ์ด n+1์ ๋ฐฐ์ด ํ์
ํ์ด๋ฐฉ๋ฒ:
1. ๊ธธ์ด๊ฐ n+1์ธ ans ๋ฐฐ์ด์ ์์ฑ
2. 0๋ถํฐ n๊น์ง์ ๊ฐ ์ซ์์ ๋ํด:
- hammingWeight ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ์ซ์ i๋ฅผ ์ด์ง์๋ก ๋ณํํ์ ๋ 1์ ๊ฐ์ ๊ณ์ฐ
- ๊ฒฐ๊ณผ๋ฅผ ans[i]์ ์ ์ฅ
3. ans ๋ฐฐ์ด ๋ฐํ
"""
class Solution:
def countBits(self, n: int) -> List[int]:
ans = [0] * (n+1)
for i in range(n+1):
ans[i] = self.hammingWeight(i)
return ans
def hammingWeight(self, n: int) -> int:
count = 0
while n:
count += n & 1
n >>= 1
return count