2019-11-02 12:07:41 +08:00
|
|
|
|
# 15. 二进制中 1 的个数
|
|
|
|
|
|
2020-11-05 00:45:34 +08:00
|
|
|
|
## 题目链接
|
|
|
|
|
|
|
|
|
|
[牛客网](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)
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
|
|
|
|
输入一个整数,输出该数二进制表示中 1 的个数。
|
|
|
|
|
|
2020-11-05 00:45:34 +08:00
|
|
|
|
### 解题思路
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
2020-11-05 00:45:34 +08:00
|
|
|
|
n&(n-1) 位运算可以将 n 的位级表示中最低的那一位 1 设置为 0。不断将 1 设置为 0,直到 n 为 0。时间复杂度:O(M),其中 M 表示 1 的个数。
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
2020-11-05 00:45:34 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20201105004127554.png" width="500px"> </div><br>
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public int NumberOf1(int n) {
|
|
|
|
|
int cnt = 0;
|
|
|
|
|
while (n != 0) {
|
|
|
|
|
cnt++;
|
|
|
|
|
n &= (n - 1);
|
|
|
|
|
}
|
|
|
|
|
return cnt;
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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>
|