对于正数,负数可能会陷入死循环
int numberOf1(int n){
int count = 0;
while(n){
if(n & 1) //判断最后一位是否为1
count++;
n = n >> 1;
}
return count;
}
此种方法可适用于正数和负数,而且不会陷入死循环
int numberOf1(int n){
int count = 0;
unsigned int flag = 1;
while(flag){
if(n & flag)
count++;
flag = flag << 1;
}
return count;
}
新的解法
int numberOf1(int n){
int count = 0;
while(n){
++count;
n = (n - 1) & n; //将最右边的1变为0
}
return count;
}