/*
* 整数的二进制表达式中有多少个1
* 给定一个三十二位的整数n,返回该整数二进制中的1的个数
*
* 解题思路
* 一
* 每次判断最右一位是否为1,然后再无符号右移
*
* 二
* n=n&(n-1)
*
* 三
* 平行算法
* */
public class BO4 {
public int count1(int n)
{
int res=0;
while (n!=0){
res+=n&1;
n>>>=1;
}
return res;
}
public int count2(int n){
int res=0;
while (n!=0){
n&=(n-1);
res++;
}
return res;
}
public int count3(int n)
{
n=(n&0x55555555)+((n>>>1)&0x55555555);
n=(n&0x33333333)+((n>>>1)&0x33333333);
n=(n&0x0f0f0f0f)+((n>>>1)&0x0f0f0f0f);
n=(n&0x00ff00ff)+((n>>>1)&0x00ff00ff);
n=(n&0x0000ffff)+((n>>>1)&0x0000ffff);
return n;
}
}