zoukankan      html  css  js  c++  java
  • Codeforces Round #320 (Div. 2) [Bayan Thanks-Round] A. Raising Bacteria【位运算/二进制拆分/细胞繁殖,每天倍增】

    A. Raising Bacteria
    time limit per test
    1 second
    memory limit per test
    256 megabytes
    input
    standard input
    output
    standard output

    You are a lover of bacteria. You want to raise some bacteria in a box.

    Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly 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

    The only line containing one integer x (1 ≤ x ≤ 109).

    Output

    The only line containing one integer: the answer.

    Examples
     
    input
    5
    output
    2
    input
    8
    output
    1
    Note

    For the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.

    For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.

    【题意】:在培养皿中,每个细胞每天会繁殖,数量*2 ,我们可以在任意天加入任意数量的细胞入培养皿中。 想要知道最少加入多少个细胞,可以使得有一天,培养皿中细胞的数量会恰好为x。

    【分析】:x的二进制表示中1的个数即为答案.

    原因是,每天晚上细胞数量翻倍,相当于左移1位,这时候二进制表示中1的数量不变。也就是说,二进制表示中的所有的1,一定都是添加进去的。而且也只有二进制表示中的1是添加进去的。所以二进制表示中1的数量,就是添加的细胞数。

    【代码】:

    #include<bits/stdc++.h>
    using namespace std;
    int n,m,cnt;
    
    int main()
    {
        while(cin>>n)
        {
            cnt=0; //多组输入内置清零
            while(n)
            {
                if(n%2==1)
                    cnt++;
                n/=2;
            }
            cout<<cnt<<endl;
        }
        return 0;
    }
    位运算/二进制
  • 相关阅读:
    新经资讯项目业务逻辑梳理
    HTTP状态保持的原理
    CSRF的原理和防范措施
    装饰器路由具体实现梳理
    Flask中异常捕获
    正则匹配路由
    (搬运以学习)flask 上下文的实现
    flask之请求钩子
    如何在linux中创建虚拟环境
    面包屑导航
  • 原文地址:https://www.cnblogs.com/Roni-i/p/7954527.html
Copyright © 2011-2022 走看看