您的位置:首页 > 大数据 > 人工智能

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

2017-05-29 14:46 435 查看


Problem J : Raising Bacteria

From: DHUOJ, 2016060702

Submit (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 xx 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 xx (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


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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐