1- ### 191. Number of 1 Bits
1+ # 191. Number of 1 Bits
22
3- 题目:
3+ ** < font color = red >难度: Easy</ font > **
44
5- < https://leetcode.com/problems/number-of-1-bits/ >
5+ ## 刷题内容
66
7+ > 原题连接
78
8- 难度:
9+ * https://leetcode.com/problems/number-of-1-bits/description/
910
10- Easy
11+ > 内容描述
12+
13+ ```
14+ Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
15+
16+ Example 1:
17+
18+ Input: 11
19+ Output: 3
20+ Explanation: Integer 11 has binary representation 00000000000000000000000000001011
21+ Example 2:
22+
23+ Input: 128
24+ Output: 1
25+ Explanation: Integer 128 has binary representation 00000000000000000000000010000000
26+ ```
27+
28+ ## 解题方案
29+
30+ > 思路 1
31+ ****** - 时间复杂度: O(1)****** - 空间复杂度: O(1)******
1132
1233
1334转成二进制,数1的个数
@@ -22,7 +43,8 @@ class Solution(object):
2243 return bin (n).count(' 1' )
2344```
2445
25-
46+ > 思路 2
47+ ****** - 时间复杂度: O(1)****** - 空间复杂度: O(1)******
2648
2749有wikipedia的题目 [ Hamming Weight] ( (https://zh.wikipedia.org/wiki/汉明重量) )
2850
@@ -32,13 +54,17 @@ class Solution(object):
3254
3355原理是在于每次使用x & x-1 总会把低位的数字给置0
3456
35- 比如 3 = 011 2 = 010 3 & 2 = 010 cnt =1
36-
37- 2 = 010 1 = 001 2 & 1 = 000 cnt = 2
38-
39- 比如 9 = 1001 8 = 1000 9&8 = 1000 cnt =1
57+ 比如
58+ ```
59+ 3 = 011 2 = 010 3 & 2 = 010 cnt = 1
60+ 2 = 010 1 = 001 2 & 1 = 000 cnt = 2
61+ ```
4062
41- 8 = 1000 7 = 0111 8&7 = 0000 cnt = 2
63+ 比如
64+ ```
65+ 9 = 1001 8 = 1000 9&8 = 1000 cnt = 1
66+ 8 = 1000 7 = 0111 8&7 = 0000 cnt = 2
67+ ```
4268
4369> 减1操作将最右边的符号从0变到1,从1变到0,与操作将会移除最右端的1。如果最初X有N个1,那么经过N次这样的迭代运算,X将减到0。下面的算法就是根据这个原理实现的。
4470
@@ -59,8 +85,8 @@ class Solution(object):
5985 """
6086 cnt = 0
6187 while n != 0 :
62- n &= n - 1
63- cnt += 1
64- return cnt
88+ n &= n - 1
89+ cnt += 1
90+ return cnt == 1
6591```
6692
0 commit comments