C语言 定义一个函数,可以求得一个int型数据32位中1的个数
答案vs2013#include"stdio.h"intnData(intnNum);intmain(intargc,char*argv[]){intn=0;scanf_...
答案
vs2013
#include
"stdio.h"
int nData(int nNum);
int main(int argc,
char *argv[])
{
int
n = 0;
scanf_s("%d",&n);
printf("%d",
nData(n));
return
0;
}
int nData(int nNum)
{
int
sum = 0;
for
(int i = 0; i < 32; i++)
{
if
((nNum >> i & 1) == 1)
{
sum++;
}
}
return
sum;
} 展开
vs2013
#include
"stdio.h"
int nData(int nNum);
int main(int argc,
char *argv[])
{
int
n = 0;
scanf_s("%d",&n);
printf("%d",
nData(n));
return
0;
}
int nData(int nNum)
{
int
sum = 0;
for
(int i = 0; i < 32; i++)
{
if
((nNum >> i & 1) == 1)
{
sum++;
}
}
return
sum;
} 展开
1个回答
2016-08-13
展开全部
#include <stdio.h>
int func(unsigned long x)
{
int countx = 0;
while(x)
{
countx++;
x = x&(x-1);
}
return countx;
}
int main(void)
{
unsigned long x;
scanf("%lu",&x);
printf("%d\n",func(x));
return 0;
}
追问
看清题目,int型数据
追答
#include <stdio.h>
int func(int x)
{
int countx = 0;
while(x)
{
countx++;
x = x&(x-1);
}
return countx;
}
int main(void)
{
int x;
scanf("%d",&x);
printf("%d\n",func(x));
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询