算法概述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
一、第一种实现
这也是比较多人使用的一种算法。
public static int bitCount(int i) {
int count = 0;
while(i!=0){
count++;
i = (i-1)&i;
}
return count;
}
二、第二种实现
查看Integer类,发现其中提供了一个bitCount接口,具体的实现如下:
/**
* Returns the number of one-bits in the two's complement binary
* representation of the specified {@code int} value. This function is
* sometimes referred to as the <i>population count</i>.
*
* @param i the value whose bits are to be counted
* @return the number of one-bits in the two's complement binary
* representation of the specified {@code int} value.
* @since 1.5
*/
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
三、进行效率比较。
1、将0~99999这100000个数据作为测试用例,得到结果:
2、将0~299999这300000个数据作为测试用例,得到结果:
3、将0~499999这500000个数据作为测试用例,得到结果:
4、将0~999999这1000000个数据作为测试用例,得到结果:
5、将0~9999999这10000000个数据作为测试用例,得到结果:
6、将0~99999999这100000000个数据作为测试用例,得到结果:
7、将0~999999999这1000000000个数据作为测试用例,得到结果:
四、总结。
在少量的数据处理时,方法1的效率比方法2高一些。在数据量大于500000时,数据量越大,方法2(也就是Integer提供的Api)的优势越明显,它的运行时间很稳定,不会随数据量的增大而发现较大改变。