C语言 计算二进制数中 1 的个数

#include 
#include 
#include 


// 计算 二进制 表示里头的 ‘1’ 的个数

// 时间复杂度为 O (m) , m 为 bit 1 的个数
unsigned int popcnt (unsigned int num)
{
    unsigned int ret = 0;
    while (num)
        {
        num = (num & (num - 1));    // 将 num 最右边的 1 清除
        ret ++;
        }
    return ret;
}

// 时间复杂度为 O (lg N) , N 为位数
unsigned int popcount (unsigned int  num)
{
    num = (num & 0x55555555) + ((num >> 1) & 0x55555555);
    num = (num & 0x33333333) + ((num >> 2) & 0x33333333);
    num = (num & 0x0F0F0F0F) + ((num >> 4) & 0x0F0F0F0F);
    num = (num & 0x00FF00FF) + ((num >> 8) & 0x00FF00FF);
    num = (num & 0x0000FFFF) + ((num >> 16) & 0x0000FFFF);
    return num;
}


int main(void)
{

	printf("sum(1)=%d\n", popcount(0xF0F));
	printf("sum(1)=%d\n", popcnt(0xF0F));

	return 0;
}

 

你可能感兴趣的:(笔试题)