LeetCode/solutions/191. Number of 1 Bits.md
2019-09-13 23:08:41 +08:00

53 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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++
## 思路一
``` C++
// 方法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;
}
};
```
## 思路二*
``` C++
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n) {
n &= (n - 1); // 去掉最后的1
count++;
}
return count;
}
};
```