2018-10-23 12:39:17 +00:00
|
|
|
|
# [191. Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/description/)
|
|
|
|
|
# 思路
|
|
|
|
|
## 思路一
|
|
|
|
|
不断循环,每次循环得到最低位的值,最后可得到所有位1的个数。怎样得到最低位的值,两种方法:
|
|
|
|
|
* 1、若num为奇数,则num的最低位肯定为1;
|
|
|
|
|
* 2、用一个只有低位是1的mask与num进行与操作即可得到最低位;
|
|
|
|
|
## 思路二*
|
|
|
|
|
依然是循环,但是每次循环不是得到最低位的值,而是每次循环去掉一个1,用一个count计数即可得到答案。
|
|
|
|
|
# C++
|
|
|
|
|
## 思路一
|
2019-09-13 15:08:41 +00:00
|
|
|
|
``` C++
|
2018-10-23 12:39:17 +00:00
|
|
|
|
// 方法1
|
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
int hammingWeight(uint32_t n) {
|
|
|
|
|
int res = 0;
|
|
|
|
|
while(n != 0){
|
|
|
|
|
res += (n % 2);
|
|
|
|
|
n /= 2;
|
|
|
|
|
}
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// 方法2
|
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
int hammingWeight(uint32_t n) {
|
|
|
|
|
int res = 0;
|
|
|
|
|
uint32_t mask = 1;
|
|
|
|
|
for(int i = 0; i < 32; i++){
|
|
|
|
|
res += (n & mask);
|
|
|
|
|
n = n >> 1;
|
|
|
|
|
}
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
```
|
|
|
|
|
## 思路二*
|
2019-09-13 15:08:41 +00:00
|
|
|
|
``` C++
|
2018-10-23 12:39:17 +00:00
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
int hammingWeight(uint32_t n) {
|
|
|
|
|
int count = 0;
|
|
|
|
|
while (n) {
|
|
|
|
|
n &= (n - 1); // 去掉最后的1
|
|
|
|
|
count++;
|
|
|
|
|
}
|
|
|
|
|
return count;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
```
|