Skip to content

Commit 1bf60ce

Browse files
committed
Sync LeetCode submission - Number of 1 Bits (python3)
1 parent 24c6ef1 commit 1bf60ce

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

problems/number_of_1_bits/solution.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def hammingWeight(self, n: int) -> int:
3+
4+
# 0000000000000000000000000000 1011 ---> 2^0 + 2^1 + 2^3 = 11
5+
# &
6+
# 0000000000000000000000000000 1010 --> 2^1 + 2^3 = 10
7+
# -----------------------------------
8+
# 1010 --> 10 still
9+
10+
# 0000000000000000000000000000 1010 --> 2^1 + 2^3 = 10
11+
# &
12+
# 0000000000000000000000000000 1001 --> 2^0 + 2^3 = 9
13+
# -----------------------------------
14+
# 1000 --> 8
15+
16+
# 0000000000000000000000000000 1000 -> 2^3 = 8
17+
# &
18+
# 0000000000000000000000000000 0101 -> 2^0 + 2^1 + 2^2 = 7
19+
# -----------------------------------
20+
# 0 -> 0
21+
22+
ans = 0
23+
while n != 0:
24+
ans += 1
25+
n &= n-1
26+
return ans
27+
28+
29+

0 commit comments

Comments
 (0)