码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-10-28 15:44:35      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:system   二进制   return   count   


方法一:

#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 的个数

标签:system   二进制   return   count   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!