首页 > 其他 > 详细

一个函数返回参数二进制中 1 的个数

时间:2015-10-28 15:43:42      阅读:165      评论:0      收藏:0      [点我收藏+]

方法一:

#include<stdio.h>


int bit_count(unsigned int n)

{

int count;

for (count = 0; n; n &= n - 1)

{

count++;

}

return count;

}

int main()

{

int y;

int c;

printf("请输入一个数:");

scanf("%d", &c);

y = bit_count(c);

printf("%d\n", y);

system("pause");

return 0;

}



方法二:

#include<stdio.h>

int bit_count(unsigned int n)

{

int count=0;

int i = 32;

while (i)

{

if (n & 1 == 1)

{

count++;

n >>= 1;

}

i--;

}

return count;


}

int main()

{

int y;

int c;

printf("请输入一个数:");

scanf("%d", &c);

y = bit_count(c);

printf("%d\n", y);

system("pause");

return 0;

}






本文出自 “fun” 博客,请务必保留此出处http://10725723.blog.51cto.com/10715723/1707219

一个函数返回参数二进制中 1 的个数

原文:http://10725723.blog.51cto.com/10715723/1707219

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!