Codeforces 579A. Raising Bacteria Solution
Explain: Here ,we look that n bacteria split in the night.Always time it's split to 2x .
That's means 1*2 >2*2>2*2*2>2*2*2*2>......... if we convert binary representation
10> 100>1000>10000
example:
input :5
output:2
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.
input :8
output:1
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.
5 's binary representation 101
also 8 s binary representation 1000
we understand that number of 1 (binary representation ) is the minimum number of bacteria we put.
For finding number of 1 we can use __builtin_popcount(x): This function is used to count the number of one’s(set bits) in an integer.
Solution in C++:
///La ilaha illellahu muhammadur rasulullah
///******Bismillahir-Rahmanir-Rahim******///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- int n;
- cin>>n;
- cout<<__builtin_popcount(n)<<endl;
- }
Another solution:
- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- int n,i,c=0,r;
- cin>>n;
- while(n>0)
- {
- c+=n%2;
- n/=2;
- }
- cout<<c<<endl;
- }
No comments