CODEFORCES Raising Bacteria 饲养细菌 只要你能理解,代码超简单

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_34678439/article/details/53558985

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.

Example
Input
5
Output
2
Input
8
Output
1


原题链接:http://codeforces.com/problemset/problem/579/A

题目很简单,但是还是担心部分朋友因为数据的问题怀疑自己看不懂给题目,所以咱还是来做个简单的翻译吧!

你是个细菌爱好者(是不是有点难以接受?),你想要在盒子里饲养一些细菌。首先盒子是空的。你每天早上会放一些细菌到盒子里,每到了晚上,盒子里的每个细菌就会分裂成两个。有些时候你知道了盒子里确切的细菌数量x。要问这些天你最少往盒子里放了多少个细菌。

当你知道盒子里有5个细菌时,那么这些天你最少往盒子里放了2个细菌。若盒子里有8个细菌,则这些天你最少往盒子里放了1个细菌。

看起来很不可思议?没关系,我们来分析一下。1个细菌一个晚上分裂为2个,两个晚上就4个,只要第三天再放入一个那就是五个细菌啦,但是实际上我们从盒子外面放进去的是2个。那8个细菌是怎么来的呢,嘿嘿,1个细菌分裂4个晚上就可以了哦。

看明白了吗?跟2的倍数相关的哦。下面我们用位运算进行解题,超简单!

#include <stdio.h>
#include <math.h>

int main()
{
    int a;
    int summ=0;
    scanf("%d", &a);
    while(a)
    {
        if(a&1) summ++;   //a&1 是a和1进行与运算,意思是当a的二进制与1相与为1,则summ++。只要a的二进制的最低位是1,则与1相与就是1。
        a>>=1;   //a的二进制向右移一位,就是十进制的a除以2。
    }
    printf("%d\n",summ);

    return 0;    
}


嘿嘿,有没有被吓到?就是这么简单!


猜你喜欢

转载自blog.csdn.net/baidu_34678439/article/details/53558985
今日推荐