Skip to content

Commit c16c8b3

Browse files
committed
feat: add number-of-1-bits solution
1 parent eedb8e6 commit c16c8b3

File tree

1 file changed

+44
-4
lines changed

1 file changed

+44
-4
lines changed

number-of-1-bits/shinsj4653.py

+44-4
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,53 @@
11
"""
22
[문제풀이]
33
# Inputs
4-
4+
- 양인 정수 n
55
# Outputs
6-
6+
- number of set bits => 이진수 값의 1 개수
77
# Constraints
8-
8+
- 1 <= n <= 2^31 - 1
99
# Ideas
10+
1. 반복문
11+
2로 나눠서 몫 나머지 -> 나머지가 1인지 0인지 체크
12+
그 몫을 또 2로 나눠서 몫, 나머지 ->
13+
14+
15+
11
16+
2-> 5, 1
17+
2-> 2, 1
18+
2-> 1, 0
19+
2-> 0, 1
20+
21+
몫이 0이 될 때 까지 반복
22+
23+
TC: log2N? SC: 1
1024
1125
[회고]
26+
시간 복잡도가 log2N인가?
27+
-> O
28+
29+
해설은 어떤지 궁금
30+
->
31+
32+
"""
33+
34+
class Solution:
35+
def hammingWeight(self, n: int) -> int:
36+
ret = 0
37+
while n > 0:
38+
n, bit = n // 2, n % 2
39+
if bit == 1:
40+
ret += 1
41+
42+
return ret
43+
44+
# 해설
45+
46+
class Solution:
47+
def hammingWeight(self, n: int) -> int:
48+
cnt = 0
49+
while n:
50+
cnt += n & 1
51+
n >>= 1
52+
return cnt
1253

13-
"""

0 commit comments

Comments
 (0)