Skip to content

Commit 0bc5262

Browse files
committed
Solve LC > numbers-of-1-bits
1 parent 5639aa5 commit 0bc5262

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

number-of-1-bits/bemelon.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def hammingWeight_v1(self, n: int) -> int:
3+
# Recursive solution
4+
# Time complexity: O(log n)
5+
# Space complexity: O(log n)
6+
if n == 0: return 0
7+
elif n % 2 == 0: return self.hammingWeight(n // 2)
8+
else: return self.hammingWeight(n // 2) + 1
9+
10+
def hammingWeight(self, n: int) -> int:
11+
# Iterative solution
12+
# Time complexity: O(log n)
13+
# Space complexity: O(1)
14+
set_bit_cnt = 0
15+
while n > 0:
16+
set_bit_cnt += n & 1
17+
n >>= 1
18+
return set_bit_cnt

0 commit comments

Comments
 (0)