Skip to content

Commit e5ce8a0

Browse files
committed
📝 docs : add 191. Number of 1 Bits.md
1 parent 730aa7c commit e5ce8a0

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
## 191. 位1的个数
2+
> https://leetcode-cn.com/problems/number-of-1-bits/
3+
4+
5+
### Java
6+
```java
7+
/*
8+
* @Author: Goog Tech
9+
* @Date: 2020-08-16 10:07:51
10+
* @LastEditTime: 2020-08-16 10:08:33
11+
* @Description: https://leetcode-cn.com/problems/number-of-1-bits/
12+
* @FilePath: \leetcode-googtech\#191. Number of 1 Bits\Solution.java
13+
* @WebSite: https://algorithm.show/
14+
*/
15+
16+
public class Solution {
17+
// you need to treat n as an unsigned value
18+
public int hammingWeight(int n) {
19+
// 使用与(&)运算,即两位同时为1时结果才为1
20+
return n == 0 ? 0 : 1 + hammingWeight(n & (n - 1));
21+
}
22+
}
23+
```
24+
25+
### Python
26+
```python
27+
'''
28+
Author: Goog Tech
29+
Date: 2020-08-16 10:07:58
30+
LastEditTime: 2020-08-16 10:08:49
31+
Description: https://leetcode-cn.com/problems/number-of-1-bits/
32+
FilePath: \leetcode-googtech\#191. Number of 1 Bits\Solution.py
33+
WebSite: https://algorithm.show/
34+
'''
35+
36+
class Solution(object):
37+
def hammingWeight(self, n):
38+
"""
39+
:type n: int
40+
:rtype: int
41+
"""
42+
count = 0
43+
# bin() 返回一个整数 int 或者长整数 long int 的二进制表示
44+
for i in str(bin(n)):
45+
if i == '1': count += 1
46+
return count
47+
```

docs/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
* [160.相交链表](LeetCod刷题之旅及题目解析/160.相交链表/160.相交链表.md)
4949
* [167.两数之和II-输入有序数组](LeetCod刷题之旅及题目解析/167.两数之和II-输入有序数组/167.两数之和II-输入有序数组.md)
5050
* [182.查找重复的电子邮箱](LeetCod刷题之旅及题目解析/182.查找重复的电子邮箱/182.查找重复的电子邮箱.md)
51+
* [191.位1的个数](LeetCod刷题之旅及题目解析/191.位1的个数/191.位1的个数.md)
5152
* [203.移除链表元素](LeetCod刷题之旅及题目解析/203.移除链表元素/203.移除链表元素.md)
5253
* [222.完全二叉树的节点个数](LeetCod刷题之旅及题目解析/222.完全二叉树的节点个数/222.完全二叉树的节点个数.md)
5354
* [226.翻转二叉树](LeetCod刷题之旅及题目解析/226.翻转二叉树/226.翻转二叉树.md)

0 commit comments

Comments
 (0)