/** * 快速计算二进制数中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; } }
如对本文有疑问, 点击进行留言回复!!
【奥鹏作业答案库网】大工20春《应用统计》在线作业1【奥鹏作业答案】
网友评论