Skip to content

Commit acc6d7e

Browse files
committed
number of 1 bits solution
1 parent c12a07f commit acc6d7e

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

number-of-1-bits/yerim01.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Goal: Given a positive int n, return the number of set bits in binary.
2+
# Approach:
3+
# Divide by 2 and check the remainder to determine the last bit.
4+
# If the remainder is 1, update the variable 'count'.
5+
# Repeat until n becomes 0.
6+
# Time Complexity: O(logn)
7+
# - We process each bit of n.
8+
# Space Complexity: O(1)
9+
# - We use only one variable 'count'.
10+
class Solution:
11+
def hammingWeight(self, n: int) -> int:
12+
count = 0
13+
14+
while n != 0:
15+
if n % 2 == 1:
16+
count += 1
17+
n = n // 2
18+
19+
return count

0 commit comments

Comments
 (0)