Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)
/**
*快速计算二进制数中1的个数(FastBitCounting)
*该算法的思想如下:
*每次将该数与该数减一后的数值相与,从而将最右边的一位1消掉
*直到该数为0
*中间循环的次数即为其中1的个数
*例如给定"10100“,减一后为”10011",相与为"10000",这样就消掉最右边的1
*SparseOnesandDenseOneswerefirstdescribedbyPeterWegnerin
*“ATechniqueforCountingOnesinaBinaryComputer“,
*CommunicationsoftheACM,Volume3(1960)Number5,page322
*/
packageal;
publicclassCountOnes{
publicstaticvoidmain(String[]args){
inti=7;
CountOnescount=newCountOnes();
System.out.println("Thereare"+count.getCount(i)+"onesini");
}
/**
*@author
*@parami待测数字
*@return二进制表示中1的个数
*/
publicintgetCount(inti){
intn;
for(n=0;i>0;n++){
i&=(i-1);
}
returnn;
}
}热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志