返回

求二进制数中 1 的个数

发布时间:2022-11-11 11:26:24 256
# java# java

原文地址:求二进制数中 1 的个数

欢迎访问我的博客:http://blog.duhbb.com/

引言

有很多中方法可以计算一个整数二进制形式中的 1 的个数, 本文记录两种, 速度都还不错. 第一个算法好记一点, 理解起来也简单, 应该是首选了.

位移法

int BitCount(unsigned int n)
{
    unsigned int c = 0;
    for (c = 0; n; ++c)
    {
        // 清除最低位的 1
        n &= (n - 1);
    }
    return c;
}

JDK 中 Integer 的方法

    /**
     * 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 population count.
     *
     * @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;
    }

在 C++ 中把 >>> 换成 >>.

结束语

这篇博客 算法-求二进制数中 1 的个数 中记录了好几种不同的算法, 大家感兴趣可以移步这里.

原文地址:求二进制数中 1 的个数

欢迎访问我的博客:http://blog.duhbb.com/

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线