We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c12a07f commit acc6d7eCopy full SHA for acc6d7e
1 file changed
number-of-1-bits/yerim01.py
@@ -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