欢迎访问我的个人博客:我心永恒

求二进制数中 1 的个数

原文地址:求二进制数中 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 <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;
    }

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

结束语

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

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

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

posted @   tuhooo  阅读(68)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现

欢迎访问我的个人博客:我心永恒

点击右上角即可分享
微信分享提示