Java实例4 - 快速计算二进制数中1的个数(Fast Bit Counting)

来源:互联网 发布:游戏源码论坛 编辑:程序博客网 时间:2024/05/21 07:04
[java] view plaincopy
  1. /** 
  2.  * 快速计算二进制数中1的个数(Fast Bit Counting) 
  3.  * 该算法的思想如下: 
  4.  * 每次将该数与该数减一后的数值相与,从而将最右边的一位1消掉 
  5.  * 直到该数为0 
  6.  * 中间循环的次数即为其中1的个数 
  7.  * 例如给定"10100“,减一后为”10011",相与为"10000",这样就消掉最右边的1 
  8.  * Sparse Ones and Dense Ones were first described by Peter Wegner in  
  9.  * “A Technique for Counting Ones in a Binary Computer“,  
  10.  * Communications of the ACM, Volume 3 (1960) Number 5, page 322 
  11.  */  
  12. package al;  
  13. public class CountOnes {  
  14.     public static void main(String[] args) {  
  15.         int i = 7;  
  16.         CountOnes count = new CountOnes();  
  17.         System.out.println("There are " + count.getCount(i) + " ones in i");  
  18.     }  
  19.     /** 
  20.      * @author  
  21.      * @param i 待测数字 
  22.      * @return 二进制表示中1的个数 
  23.      */  
  24.     public int getCount(int i) {          
  25.         int n;  
  26.         for(n=0; i > 0; n++) {  
  27.             i &= (i - 1);  
  28.         }         
  29.         return n;         
  30.     }  
  31. }  
0 0
原创粉丝点击