Problem J : Raising Bacteria
From: DHUOJ, 2016060702
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
分析
根据题目要求,不用考虑时间的长短,只用将投入数目减到最少即可。所以可以从最终数目考虑,如果最后数目为奇数,则最后一天肯定投入了一个,因为每天的个数是前一天个数的两倍加上当天投入的数目,同理判断倒数第二天是否为奇数,以此往前推,如果为奇数,则总投入量++,如果为偶数继续循环,直到数目为1的那一天跳出循环,由于第一天的1只也是投入的,所以初始的投入量应该为1。
代码
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
int main()
{
int x;
while(~scanf("%d",&x))
{
int sum=1;//定义初始投入量为1
while(x!=1)//当数目不为1,则说明还没有计算到第一天
{
if(x%2!=0)//如果当天的数目为奇数说明当天投入了
{
x--;
sum++;//因为要求最小投入量,所以每次加1,最后会使得总量最小
}
x=x/2;//将当天数目变为前一天的数目
}
printf("%d\n",sum);
}
}