star

搜索

RSS

RSS Link

计数器

133738
高精度除法器
求平面最近点对

求一个数的二进制有多少个1?

Star posted @ 2010年8月03日 02:29 in C语言 with tags c 分治 位运算 二进制 , 3127 阅读
/*author:Star date:2010-08-02*/
#include <stdio.h>
#include <assert.h>

int CntBit(unsigned int n)	//分治思想
{
	n = ((n & 0xaaaaaaaa) >> 1 ) + (n & 0x55555555);
	n = ((n & 0xcccccccc) >> 2 ) + (n & 0x33333333);
	n = ((n & 0xf0f0f0f0) >> 4 ) + (n & 0x0f0f0f0f);
	n = ((n & 0xff00ff00) >> 8 ) + (n & 0x00ff00ff);
	n = ((n & 0xffff0000) >> 16) + (n & 0x0000ffff);
	return n;
}

int main(int argc, char *argv[])
{
	unsigned int N;
	int i, j;
	scanf("%u", &N);
	printf("%u:", N);
	i = CntBit(N);
	assert(i >= 0 && i <= 32);
	for(j = 31; j >= 0; --j)
		printf("%d", N&(1<<j) ? 1 : 0);	
	printf("\nhave %d bit that are \'1\'", i);
	return 0;
}

这里数以$$2^{32}-1$$的大小范围为例。

CGBSE 11th Question 说:
2022年8月25日 15:19

Important Model Question Papers for Other Subjects and the Eleventh Standard in Chhattisgarh are Available for Download Based on the Subjects List. The Class 11th Important Model Question Paper 2023 has been distributed CGBSE 11th Question Paper 2023 in both offline and online formats by the Chhattisgarh Board of Secondary Education (CGBSE). Chhattisgarh Class 11th Significant Important Model Question Paper 2023 are Available on the Official Site as well as Here. Chhattisgarh Higher Secondary Board Important Model Question Paper 2023 Subject-wise are Provided Here. Important Exam Model Question Paper 2023 are used as the Board Assessments' reference materials.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter