Skip to content

Commit 0ad52c0

Browse files
committed
solve: numberOf1Bits
1 parent 2496829 commit 0ad52c0

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

number-of-1-bits/yolophg.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)