关于后端:求二进制数中-1-的个数

0次阅读

共计 803 个字符,预计需要花费 3 分钟才能阅读完成。

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

正文完
 0