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 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 (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
我是预估10^9的2的n次方大概在30,然后把他们算出来存到数组里,把给出的数找他最接近的那个减掉,在找最近的减掉,每次减掉加一个细胞就可以了
#include <iostream>
#include <cstring>
#include <cstdio>
#include <math.h>
using namespace std;
int X[30];
int main()
{
for(int i=0;i<30;i++)
{
X[i]=pow(2,i);
}
int n;
while(scanf("%d",&n)!=EOF)
{
int count=0;
for(int i=29;i>=0;i--)
{
if(n-X[i]>=0)
{
n-=X[i];
count++;
if(n<=0) break;
}
}
printf("%d\n",count);
}
}