文章目录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

using namespace std;
//这种算法的效率是o(n),也就是n多大,就进行多少次
//int Numberof1(int n){//最好不要修改n,因为如果是负数,那么有可能会出现死循环
// int countt=0;
// unsigned int flag=1;
//
// while(flag){
// if(n & flag)//这个数与1,2,4,8相与
// countt++;
// flag=flag<<1;
// }
// return countt;
//}
//下面这种可以提交速度到o(1的个数){
int Numberof1(int n){
int countt=0;
while(n){
countt++;
n=n&(n-1);//这步操作可以消掉最右边的一位1

}
return countt;
}
int main()
{
int temp=Numberof1(13);
cout << temp<< endl;
return 0;
}
文章目录