Skip to content

Commit a69a338

Browse files
committed
Add solution for Number of 1 Bits problem
1 parent 6151023 commit a69a338

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

number-of-1-bits/gcount85.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""
2+
# Intuition
3+
n을 n-1과 AND 비트 연산하면서 1을 제거해나가며 카운트한다.
4+
5+
# Complexity
6+
- Time complexity: n의 이진수 변환에서 1의 개수를 K라고 할 때, O(K)
7+
8+
- Space complexity: O(1)
9+
"""
10+
11+
12+
class Solution:
13+
def hammingWeight(self, n: int) -> int:
14+
count = 0
15+
while n:
16+
n &= n - 1
17+
count += 1
18+
return count

0 commit comments

Comments
 (0)