The beauty of programming 1 -- the number of 1 in the binary representation of a number, the beauty of Binary
Three solutions are introduced here.
First; (conventional solution)
The number is represented in binary in the computer, so the number n can be used consecutively to divide 2
Code 1:
<Span style = "font-size: 14px;" >#include <iostream> using namespace std; int main (void) {int n, m; m = 0; cin> n; while (n) {if (n % 2) // if n cannot divide 2, the end of the current n is 1 m ++; n >>= 1; // n shifts 1 to the right, that is, n/2} cout <m <endl; return 0 ;}</span>
Second: bitwise operations
&: If a is 1 and B is 1, a & B is 1. Otherwise, a & B is 0.
Here I = 0x1 is initialized;
If n & I is 1, the end of n is 1; otherwise, it is 0.
Code 2:
<Span style = "font-size: 14px;" >#include <iostream> using namespace std; int main (void) {// bit operation, 1. the last bit of the binary is used to calculate the int n, I, m; m = 0; I = 0x1; cin> n; while (n) {m + = (n & I); n >>= 1 ;}cout <m <endl; return 0 ;}</span>
Third: use another bit operation
If the binary value of n is 0010 0000, the second algorithm needs to be improved.
Allows n and n-1 to perform the & operation. If n & (n-1) = 0, it is the above case (only one of n's binary representation is 0 ).
Code 3:
<span style="font-size:14px;">#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;}</span>