/** * 快速計算二進制數中1的個數(Fast Bit Counting) * 該算法的思想如下: * 每次將該數與該數減一后的數值相與,從而將最右邊的一位1消掉 * 直到該數為0 * 中間循環的次數即為其中1的個數 * 例如給定"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 待測數字 * @return 二進制表示中1的個數 */ public int getCount(int i) { int n; for(n=0; i > 0; n++) { i &= (i - 1); } return n; } }
新聞熱點
疑難解答