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 入住酒店文案祝福语简短