###### tags: `Leetcode`
# 0191. 位1的个数
Link: https://leetcode-cn.com/problems/number-of-1-bits/solution/wei-1de-ge-shu-by-leetcode-solution-jnwf/
## 思路
## Keypoints
## Code in C++
## Code in Java
```java=
public class Solution {
public int hammingWeight(int n) {
int ret = 0;
for (int i = 0; i < 32; i++) {
if ((n & (1 << i)) != 0) {
ret++;
}
}
return ret;
}
}
```
## 思路
每一位进行与运算
## 思路2
```n & (n−1)```,其运算结果恰为把 ```n``` 的二进制位中的最低位的 1 变为 0 之后的结果。
```java=
public class Solution {
public int hammingWeight(int n) {
int ret = 0;
while (n != 0) {
n &= n - 1;
ret++;
}
return ret;
}
}
```