package 比特位计数; class A { public int[] countBits(int n) { int[] bits =new int [n+1]; for(int i=0;i<=n;i++){ bits[i]=count(i); } return bits; } public int count(int i){ int one=0; while(i>0){ i &=(i-1); one++; } return one; } } //定义一个数组 //for循环存数,调用方法存值 //&= 一次去一个1
比特位计数
最新推荐文章于 2024-08-11 20:00:32 发布
该代码定义了一个名为A的类,其中包含两个方法:countBits和count。countBits方法用于生成一个数组,数组的每个元素表示对应整数的二进制表示中1的个数。count方法通过位操作计算一个整数i中1的个数,使用while循环和位与运算(&)逐次移位并累加。
摘要由CSDN通过智能技术生成