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

求二进制数中 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 @ 2022-06-17 15:32  tuhooo  阅读(57)  评论(0编辑  收藏  举报

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