Skip to content

Commit 175a780

Browse files
committed
feat: [Week 08-1] solve number of 1 bits
1 parent 559a27b commit 175a780

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

number-of-1-bits/Chaedie.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
"""
2+
Solution:
3+
1) 숫자에 1 bit 을 and 연산 결과가 1일 경우 result 에 1을 더한다.
4+
2) n 을 오른쪽으로 쉬프팅 시킨다.
5+
6+
N: n의 bit 수
7+
Time: O(N)
8+
Space: O(1)
9+
10+
"""
11+
12+
13+
class Solution:
14+
def hammingWeight(self, n: int) -> int:
15+
result = 0
16+
while n > 0:
17+
if n & 1:
18+
result += 1
19+
n = n >> 1
20+
return result

0 commit comments

Comments
 (0)