把1循环左移,同时和原数字做&操作,直到1变成0
1
2
3
4
5
6
7
8
9
10
11int numberOfOne(int number)
{
int count = 0;
int flag = 1;
while (flag)
{
if (number & flag) count++;
flag <<= 1;
}
return count;
}一个整数number&(number)结果是将number最右侧的1变为0
1
2
3
4
5
6
7
8
9
10int numberOfOne(int number)
{
int count=0;
while (number)
{
number &= (number - 1);
count++;
}
return count;
}