2017年上海金马五校程序设计竞赛(网上资格赛)Problem J : Raising Bacteria

Problem J : Raising Bacteria


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  (1x109) (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);
    }
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值