输入一个整数,求该整数的二进制表达中有多少个1。例如输入10,由于其二进制表示为1010,有两个1,因此输出2。
这个题非常简单,考的是位运算,我们每次向左移1位,判断最后一位是不是1就可以了。不多说了,代码如下:
#include <stdio.h>
int count_one(int x)
{
int count = 0;
while (x != 0)
{
if (x&1 == 1)
count ++;
x = x>>1;
}
return count;
}
int main()
{
printf("%d ", count_one(3));
return 0;
}