C语言快速计算出一个无符号数一共有多少个“”1”位数的方法
C语言快速计算出一个无符号数一共有多少个“”1”位数的方法
这里介绍C语言一种快速计算出一个无符号数一共有多少个“”1”位数的方法。核心思想是(m & (m - 1)每次调用就消除一个1,直接看下面代码。
#include
#include "stdio.h"
#include
using namespace std;
#define Is2n(x) ((x & (x - 1))? 0 : 1)
int main()
{
unsigned long int value,temp,number;
while(true)
{
printf("please input a unsigned int \n");
scanf("%d",&value);
number=0;
temp=value;
while(value>0)
{
value=(value&(value-1));
number++;
}
printf("The total of bits 1 of %d is %d \n",temp,number);
}
return 0;
}
看运行结果:
我比较笨,刚开始想了半天才明白其中的奥秘,感觉好神奇吧。
C语言快速计算出一个无符号数一共有多少个“”1”位数的方法相关教程