BitCount两种实现以及效率比较

算法概述

输入一个整数,输出该数二进制表示中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个数据作为测试用例,得到结果:
测试1

2、将0~299999这300000个数据作为测试用例,得到结果:
测试2

3、将0~499999这500000个数据作为测试用例,得到结果:
测试3

4、将0~999999这1000000个数据作为测试用例,得到结果:
测试4

5、将0~9999999这10000000个数据作为测试用例,得到结果:
测试5

6、将0~99999999这100000000个数据作为测试用例,得到结果:
测试6

7、将0~999999999这1000000000个数据作为测试用例,得到结果:
测试7

四、总结。
在少量的数据处理时,方法1的效率比方法2高一些。在数据量大于500000时,数据量越大,方法2(也就是Integer提供的Api)的优势越明显,它的运行时间很稳定,不会随数据量的增大而发现较大改变。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值