2019-11-02 12:07:41 +08:00
|
|
|
|
# 15. 二进制中 1 的个数
|
|
|
|
|
|
|
|
|
|
[NowCoder](https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=13&tqId=11164&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
|
|
|
|
输入一个整数,输出该数二进制表示中 1 的个数。
|
|
|
|
|
|
|
|
|
|
### n&(n-1)
|
|
|
|
|
|
|
|
|
|
该位运算去除 n 的位级表示中最低的那一位。
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
n : 10110100
|
|
|
|
|
n-1 : 10110011
|
|
|
|
|
n&(n-1) : 10110000
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
时间复杂度:O(M),其中 M 表示 1 的个数。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public int NumberOf1(int n) {
|
|
|
|
|
int cnt = 0;
|
|
|
|
|
while (n != 0) {
|
|
|
|
|
cnt++;
|
|
|
|
|
n &= (n - 1);
|
|
|
|
|
}
|
|
|
|
|
return cnt;
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
### Integer.bitCount()
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public int NumberOf1(int n) {
|
|
|
|
|
return Integer.bitCount(n);
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|