Time Limit: 1 s
Description
You are a lover of bacteria so you want to raise some bacteria in a box. Initially, the box is empty. Every morning, you can put any number of bacteria into the box. Every night every bacterium in the box will split into two bacteria. You hope to see exactly
x
x bacteria in the box at some moment. What is the minimum number of bacteria you need to put into the box across those days?
Input
There are several test cases. Each case contains only one integer
x
x
(1≤x≤109)
(1≤x≤109) a line.
Output
For each case, output the only line containing one integer: the answer.
Sample Input
5
8
Sample Output
2
1
Author: handoku
解题思路:题目是说有一个人他要在某个时刻看到x个细菌,首先细菌早上放一个,到晚上会繁殖成两个,问开始至少要放多少个细菌?
首先你要知道细菌每次都是2倍2倍分裂的,假如他看到的是2的n次方个(n取1,2,3........)那他最少放一个。。。
联系二进制数中的1的个数,他看到的细菌个数换成二进制就是要求的最小的放入的数目;
我的代码:
#include<iostream>
using namespace std;
int bin(int n)
{
int sum1=0;
while(n)
{
if(n%2==1)
sum1++;
n=n/2;
}
return sum1;
}
int main()
{
int x;
while(cin>>x)
{
cout<<bin(x)<<endl;
}
}