解题思路:
如果我们将原来的整数n和原来的整数减一(n-1)做&运算,得到的值n=n&(n-1),会消去最右边的一个1,变为0,那么一个整数的二进制有多少个1,就能进行多少次这种操作,最终这个数变为0。
n: 110001001
n-1: 110001000
n&(n-1):110001000
n: 110001000
n-1: 110000111
n&(n-1): 110000000
…
class Solution {
public:
int NumberOf1(int n) {
int count=0;
while(n){
count++;
n=n&(n-1);
}
return count;
}
};