#include<stdio.h>
#include<stdlib.h>
////写一个函数返回参数二进制中 1 的个数
//比如: 15 0000 1111 4 个 1
//程序原型:
//int count_one_bits(unsigned int value)
//{
// // 返回 1的位数
//}
//int count_one_bits(unsigned int n)
//{
// int i = 0;
// while (n != 0)
// {
// if (n & 1 == 1)
// {
//
// n = n>>1;
// i++;
// }
// else
// {
// n=n >> 1;
// }
// }
// return i;
//}
int count_one_bits(unsigned int n)
{
int i = 0;
int j = 0;
for (j = 0; j < 32;j++)
{
if ((n>>j) & 1 == 1)
{
i++;
}
}
return i;
}
int main()
{
int n = 20;
printf("%d", count_one_bits(n));
system("pause");
return 0;
}
两种方法,第一种不能丢else;所以在以后的编程中无论用不用得到,用了if最好都加上else。