File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
problems/number_of_1_bits Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments