Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1142f4c

Browse files
ybian19azl397985856
authored andcommitted
feat: 191.number-of-1-bits add Python3 implementation (azl397985856#114)
1 parent b332699 commit 1142f4c

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

‎problems/191.number-of-1-bits.md‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ https://leetcode.com/problems/number-of-1-bits/description/
66
```
77
Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
88
9-
9+
1010
1111
Example 1:
1212
@@ -23,7 +23,7 @@ Example 3:
2323
Input: 11111111111111111111111111111101
2424
Output: 31
2525
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
26-
26+
2727
2828
Note:
2929
@@ -36,11 +36,11 @@ In Java, the compiler represents the signed integers using 2's complement notati
3636

3737
这个题目的大意是: 给定一个无符号的整数, 返回其用二进制表式的时候的1的个数。
3838

39-
这里用一个trick, 可以轻松求出。 就是`n & (n - 1)` 可以`消除` n 最后的一个1的原理。
39+
这里用一个trick, 可以轻松求出。 就是`n & (n - 1)` 可以`消除` n 最后的一个1的原理。
4040

4141
> 为什么能消除最后一个1, 其实也比较简单,大家自己想一下
4242
43-
这样我们可以不断进行`n = n & (n - 1)`直到n === 0 , 说明没有一个1了。
43+
这样我们可以不断进行`n = n & (n - 1)`直到n === 0 , 说明没有一个1了。
4444
这个时候`我们消除了多少1变成一个1都没有了, 就说明n有多少个1了`
4545

4646
## 关键点解析
@@ -52,7 +52,7 @@ In Java, the compiler represents the signed integers using 2's complement notati
5252

5353
## 代码
5454

55-
语言支持:JS, C++
55+
语言支持:JS, C++,Python
5656

5757
JavaScript Code:
5858

@@ -137,7 +137,9 @@ var hammingWeight = function(n) {
137137
};
138138

139139
```
140+
140141
C++ code:
142+
141143
```c++
142144
class Solution {
143145
public:
@@ -152,6 +154,22 @@ public:
152154
};
153155
```
154156
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+
155173
## 扩展
156174
可以使用位操作来达到目的。例如8位的整数21:
157175

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /