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

Problem J : Raising Bacteria


 (Out of Contest)

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

 


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;
   }
 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值