2017年上海金馬五校程式設計競賽(網上資格賽)J : Raising Bacteria
阿新 • • 發佈:2019-02-14
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; } }