Raising Bacteria
From: DHUOJ, 2016060702
<button class="btn btn-default" id="submit_open_top" type="button"> Submit</button>
&lt;a type="button" class="btn btn-warning" href="/solution/submit.html?problemId=5269"&gt;Submit&lt;/a&gt; <center> Time Limit: 1 s </center>
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 exactlyx 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≤10 9 ) (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
思路:
每次模2,如果不是偶数,则需要新的一条细菌来充当这个1。然后一直除2,看这个过程中会产生几个1,就需要几条细菌。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<stack>
using namespace std;
int main()
{
int x,cnt=0;;
while(~scanf("%d",&x)){
cnt=0;
while(x>1)
{
if(x%2==1)
{
cnt++;
}
x=x/2;
}
printf("%d\n",cnt+1);
}
return 0;
}