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 大厦动工祝福语简短精辟