/** * 快速計算二進制數(shù)中1的個數(shù)(Fast Bit Counting) * 該算法的思想如下: * 每次將該數(shù)與該數(shù)減一后的數(shù)值相與,從而將最右邊的一位1消掉 * 直到該數(shù)為0 * 中間循環(huán)的次數(shù)即為其中1的個數(shù) * 例如給定"10100“,減一后為”10011",相與為"10000",這樣就消掉最右邊的1 * Sparse Ones and Dense Ones were first described by Peter Wegner in * “A Technique for Counting Ones in a Binary Computer“, * Communications of the ACM, Volume 3 (1960) Number 5, page 322 */ package al; public class CountOnes { public static void main(String[] args) { int i = 7; CountOnes count = new CountOnes(); System.out.println("There are " + count.getCount(i) + " ones in i"); } /** * @author * @param i 待測數(shù)字 * @return 二進制表示中1的個數(shù) */ public int getCount(int i) { int n; for(n=0; i > 0; n++) { i &= (i - 1); } return n; } }
新聞熱點
疑難解答