写一个函数返回参数二进制中1的个数。
当看到这个题目,我的想法肯定是这样的:
#include <stdio.h>
#include <stdlib.h>
int count_one_bit(unsigned int n)
{
int count = 0;
while(n)
{
if(n%2 == 1)
{
count++;
}
n /= 2;
}
return count;
}
int main()
{
int num = 10;
int ret = count_one_bit(num);
printf("%d\n",ret);
system("pause");
return 0;
}
int count_one_bit(unsigned int n)
{
int count = 0;
int i = 0;
for(i=0; i<32; i++)
{
if(n&1 == 1)
{
count++;
}
n = n >> 1;
}
return count;
}
经过进一步的优化之后:(自我感觉代码完美)
int count_one_bit(unsigned int n)
{
int count = 0;
int i = 0;
while(n)
{
count++;
n = n & (n-1);
}
return count;
}
引申题:
判断一个数是不是2的n次方。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 7;
if((num & (num-1)) == 0)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
system("pause");
return 0;
}