File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed
LeetCod刷题之旅及题目解析/191.位1的个数 Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change 48
48
* [ 160.相交链表] ( LeetCod刷题之旅及题目解析/160.相交链表/160.相交链表.md )
49
49
* [ 167.两数之和II-输入有序数组] ( LeetCod刷题之旅及题目解析/167.两数之和II-输入有序数组/167.两数之和II-输入有序数组.md )
50
50
* [ 182.查找重复的电子邮箱] ( LeetCod刷题之旅及题目解析/182.查找重复的电子邮箱/182.查找重复的电子邮箱.md )
51
+ * [ 191.位1的个数] ( LeetCod刷题之旅及题目解析/191.位1的个数/191.位1的个数.md )
51
52
* [ 203.移除链表元素] ( LeetCod刷题之旅及题目解析/203.移除链表元素/203.移除链表元素.md )
52
53
* [ 222.完全二叉树的节点个数] ( LeetCod刷题之旅及题目解析/222.完全二叉树的节点个数/222.完全二叉树的节点个数.md )
53
54
* [ 226.翻转二叉树] ( LeetCod刷题之旅及题目解析/226.翻转二叉树/226.翻转二叉树.md )
You can’t perform that action at this time.
0 commit comments