方法一:
选择移动标志位,而不是移动原数,因为如果该数是一个负数,向右移动的时候,高位会自动补充1;
public class Solution {
public int NumberOf1(int n) {int count =0;
int flag =1;
while(flag !=0)
{
if((n & flag) != 0)
{
count++;
}
flag = flag << 1;
}
return count;
}
}
方法二:n>=1,至少一个1;n&(n-1)会使n 最右边的1变为0,直到所有1都变为0
public class Solution {
public int NumberOf1(int n) {
int count =0;while(n!=0)
{
count++;
n = n& (n-1);
}
return count;
}
}