@@ -6,7 +6,7 @@ https://leetcode.com/problems/number-of-1-bits/description/
6
6
```
7
7
Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
8
8
9
-
9
+
10
10
11
11
Example 1:
12
12
@@ -23,7 +23,7 @@ Example 3:
23
23
Input: 11111111111111111111111111111101
24
24
Output: 31
25
25
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
26
-
26
+
27
27
28
28
Note:
29
29
@@ -36,11 +36,11 @@ In Java, the compiler represents the signed integers using 2's complement notati
36
36
37
37
这个题目的大意是: 给定一个无符号的整数, 返回其用二进制表式的时候的1的个数。
38
38
39
- 这里用一个trick, 可以轻松求出。 就是` n & (n - 1) ` 可以` 消除 ` n 最后的一个1的原理。
39
+ 这里用一个trick, 可以轻松求出。 就是` n & (n - 1) ` 可以` 消除 ` n 最后的一个1的原理。
40
40
41
41
> 为什么能消除最后一个1, 其实也比较简单,大家自己想一下
42
42
43
- 这样我们可以不断进行` n = n & (n - 1) ` 直到n === 0 , 说明没有一个1了。
43
+ 这样我们可以不断进行` n = n & (n - 1) ` 直到n === 0 , 说明没有一个1了。
44
44
这个时候` 我们消除了多少1变成一个1都没有了, 就说明n有多少个1了 ` 。
45
45
46
46
## 关键点解析
@@ -52,7 +52,7 @@ In Java, the compiler represents the signed integers using 2's complement notati
52
52
53
53
## 代码
54
54
55
- 语言支持:JS, C++
55
+ 语言支持:JS, C++,Python
56
56
57
57
JavaScript Code:
58
58
@@ -137,7 +137,9 @@ var hammingWeight = function(n) {
137
137
};
138
138
139
139
```
140
+
140
141
C++ code:
142
+
141
143
``` c++
142
144
class Solution {
143
145
public:
@@ -152,6 +154,22 @@ public:
152
154
};
153
155
```
154
156
157
+ Python Code:
158
+
159
+ ```python
160
+ class Solution(object):
161
+ def hammingWeight(self, n):
162
+ """
163
+ :type n: int
164
+ :rtype: int
165
+ """
166
+ count = 0
167
+ while n:
168
+ n &= n - 1
169
+ count += 1
170
+ return count
171
+ ```
172
+
155
173
## 扩展
156
174
可以使用位操作来达到目的。例如8位的整数21:
157
175
0 commit comments