Java數據構造及算法實例:疾速盤算二進制數中1的個數(Fast Bit Counting)。本站提示廣大學習愛好者:(Java數據構造及算法實例:疾速盤算二進制數中1的個數(Fast Bit Counting))文章只能為提供參考,不一定能成為您想要的結果。以下是Java數據構造及算法實例:疾速盤算二進制數中1的個數(Fast Bit Counting)正文
/**
* 疾速盤算二進制數中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;
}
}