题意
输入一个整数,输出该二进制表示的数中1的个数
分析
方法一:
一个数减去1,就是最右边的1变成0,然后1后面变成1
1000
0111
那么当他们做与操作,结果会变成0000,这个时候就记录一个1.
方法二:
右移位法
先判断当前最后一位是否为1,就是和1做&操作
然后右移>>>,无符号的移动。
代码
public class Solution {
public int NumberOf1(int n) {
int count=0;
while(n!=0){
count++;
n=n&(n-1);
}
return count;
}
}
方法二:右边移位法,>>>无符号移位
public class Solution {
public int NumberOf1(int n) {
int count=0;
while(n!=0){
if((n&1)==1)count++;
n>>>=1;
}
return count;
}
}