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 2496829 commit 0ad52c0Copy full SHA for 0ad52c0
number-of-1-bits/yolophg.py
@@ -0,0 +1,15 @@
1
+# Time Complexity: O(k) - check each bit of n once. In the worst case, this is about 32 iterations.
2
+# Space Complexity: O(1) - only use a constant amount of extra space.
3
+
4
+class Solution:
5
+ def hammingWeight(self, n: int) -> int:
6
+ count = 0
7
8
+ # keep going till n becomes 0 (no more bits left to check)
9
+ while n:
10
+ # check if the last bit is 1 (n % 2 tells us this) and add it to the count
11
+ count += (n % 2)
12
+ # shift n to the right by 1 to move to the next bit
13
+ n = n >> 1
14
15
+ return count
0 commit comments