Here are 3 solutions to be introduced
The first kind; (Conventional solution)
The number is represented in the computer by binary, so it can be continuously use the number n to divide by 2
Code Listing 1:
#include <iostream>using namespace Std;int main (void) {int n,m; m=0; cin>>n; while (n) {if (n%2)//If n cannot be divisible by 2, indicating that the end number of the current n is 1 m++; n>>=1; n Shift right 1 bits, i.e. N/2} cout<< m <<endl; return 0;}
The second type: using bit manipulation
&: If A is 1 and B is 1, then a&b is 1, otherwise, A&b is 0
Here initializes the i=0x1;
If the n&i is 1, then the end of N is 1, otherwise 0
Code Listing 2:
#include <iostream>using namespace Std;int main (void) {//Use bit operation, 1 and binary the last one to be performed with (&) operation Int N,I,M;M=0;I=0X1;CIN&G T;>n;while (n) {m+= (n&i); n>>=1;} cout << M <<endl; return 0;}
Third: Use a different bit operation
If the binary representation of n is 0010 0000, then the second algorithm obviously needs to be improved
Allows N and n-1 to perform a & operation, if n& (n-1) ==0, the above case (the binary representation of N, only one is 0).
Code Listing 3:
#include <iostream>using namespace Std;int main (void) {int n,m;m=0;cin>>n;while (n) {n&= (n-1); m++;} cout << m <<endl;return 0;}
This article is from the "hacker" blog, make sure to keep this source http://anglecode.blog.51cto.com/5628271/1631155
The beauty of programming a number of binary representations of 1 in number