method one:
Ideas: If a number with 1 for the calculation can be found in the number of the last digit is 1, 0 otherwise.
According to this thinking can have the following code:
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 7 int n = 0; 8 cout << "输入一个数"; 9 cin >> n; 10 int count = 0; 11 while (n) 12 { 13 14 if (n & 1) 15 { 16 count++; 17 } 18 is n->> = 1 ; . 19 } 20 is COUT << " number of 1s " << COUNT << endl; 21 is return 0 ; 22 is }
But there are a few flaws in this method if the input is negative loop will be infinite die
Method Two:
N 1 and the first operation to do with determining the lowest bit of n is not 1. Then the left one obtained 1 2, n, and then do with the calculation, can determine the time n is not 1 ... low. Thus the left repeatedly, each time n can be determined which is not a solution of the 1 binary integer number of cycles equal to the number of bits, an integer of 32 to 32 cycles need
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 7 int n = 0; 8 int key = 1; 9 cout << "输入一个数"; 10 cin >> n; 11 int count = 0; 12 while (key) 13 { 14 15 if (n & key) 16 { 17 count++; 18 } 19 key <<= 1; 20 } 21 cout << "1的个数为"<<count<<endl; 22 return 0; 23 }
Method Three
Ideas: integer to a minus 1, and then to do with the original integer arithmetic, the integer will rightmost a 1 to a 0, then the binary representation of an integer has
the number 1, on how many times such an operation can be performed.
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 7 int n = 0; 8 cout << "输入一个数"; 9 cin >> n; 10 int count = 0; 11 while (n) 12 { 13 n = ((n - 1)& n); 14 count++; 15 16 } 17 cout << "1的个数为"<<count<<endl; 18 }
End of this article.
[Reserved] https://blog.csdn.net/weibo_dm/article/details/80531465