# 28、整数的二进制表示中1的个数

915人阅读 评论(0)

#include <stdio.h>

void CalNum(int n)
{
int count=0;
while (n!=0)
{
n &=n-1;
count++;
}

printf("The result is :  %d  \n\n",count);
}

int main()
{
int n;
while (printf("Input a number: "),scanf("%d",&n)!=EOF)
{
CalNum(n);
}

return 0;
}

#include <stdio.h>

void CalNum(int n)
{
int count=0;
while (n)
{
if (n&1!=0)
{
count++;
}
n>>=1;
}

printf("The result is :  %d  \n\n",count);
}

int main()
{
int n;
while (printf("Input a number: "),scanf("%d",&n)!=EOF)  //n必须为正数
{
CalNum(n);
}

return 0;
}

#include <stdio.h>

void CalNum(int n)
{
int count=0,flag=1;;
while (flag)
{
if (flag&n)
{
count++;
}
flag<<=1;
}

printf("The result is :  %d  \n\n",count);
}

int main()
{
int n;
while (printf("Input a number: "),scanf("%d",&n)!=EOF)
{
CalNum(n);
}

return 0;
}

int count_ones(unsigned a)
{
a = (a & 0x55555555) + ((a >> 1) & 0x55555555);
a = (a & 0x33333333) + ((a >> 2) & 0x33333333);
a = (a & 0x0f0f0f0f) + ((a >> 4) & 0x0f0f0f0f);
a = (a & 0x00ff00ff) + ((a >> 8) & 0x00ff00ff);
a = (a & 0x0000ffff) + ((a >> 16) & 0x0000ffff);

return a;
}

const int ones[] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2,\
3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4,\
3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2,\
3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5,\
5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5,\
6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3,\
4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3,\
3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5,\
6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6,\
5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};

int count_ones(unsigned a)
{
return (ones[a & 0xff] + ones[(a >> 8) & 0xff] + ones[(a >> 16) & 0xff]\
+ ones[(a >> 24) & 0xff]);
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：222672次
• 积分：3329
• 等级：
• 排名：第10526名
• 原创：114篇
• 转载：37篇
• 译文：0篇
• 评论：24条
评论排行
最新评论