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 5639aa5 commit 0bc5262Copy full SHA for 0bc5262
number-of-1-bits/bemelon.py
@@ -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
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