这里就不归纳移位运算的两种方法了.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x=sc.nextInt();
int count=0;
while(x!=0) {
x=(x)&(x-1);
count++;
}
System.out.println(count);
}
将1001,减去1,得到x1;x1和x进行与运算,运算一次,便消去二进制的1一个1.
step1:x-1=x1=1000.x1与x与运算得到,1000.
step2:x-1=x1=0111.x1与x与运算得到0000.
可以看见,每一步消去二进制里面的一个1.所以有多少个1,就有多少步骤.
输出count;