Method 1: judge whether the rightmost digit in the integer Binary Expression is 1, move the integer one to the right to determine whether the penultimate digit is 1, and so on until the integer is 0.
Code:
#include "stdafx.h" #include <iostream> using namespace std; int CountOf1(int n) { int nCount = 0; while (n) { if (n & 1) { nCount++; } n = n >> 1; } return nCount; } int _tmain(int argc, _TCHAR* argv[]) { cout << CountOf1(7) << endl; system("pause"); return 0; } #include "stdafx.h"#include <iostream>using namespace std; int CountOf1(int n) { int nCount = 0; while (n) { if (n & 1) { nCount++; } n = n >> 1; } return nCount; }int _tmain(int argc, _TCHAR* argv[]){cout << CountOf1(7) << endl; system("pause");return 0;}
Disadvantage: if the number of input values is negative, if the right shift operation is performed all the time, it will eventually fall into an endless loop.
Method 2: To avoid endless loops, do not shift the input number right. First, compress the input number and 1 to determine whether the digit is 1, and then shift 1 to the left, determine whether the last and second digits are 1, and so on.
Code:
#include "stdafx.h" #include <iostream> using namespace std; int CountOf1(int n) { int nCount = 0; unsigned int flag = 1; while (flag) { if (n & flag) { nCount++; } flag = flag << 1; } return nCount; } int _tmain(int argc, _TCHAR* argv[]) { cout << CountOf1(7) << endl; system("pause"); return 0; } #include "stdafx.h"#include <iostream>using namespace std; int CountOf1(int n) { int nCount = 0; unsigned int flag = 1; while (flag) { if (n & flag) { nCount++; } flag = flag << 1; } return nCount; }int _tmain(int argc, _TCHAR* argv[]){cout << CountOf1(7) << endl; system("pause");return 0;}
Disadvantage: the number of cycles is equal to the number of digits in the integer binary. 32 integers need to be cyclically 32 times.
Method 3: Subtract 1 from an integer and convert the 1 on the rightmost side of the integer to 0 after performing an operation with the original integer. How many 1 values are in the binary representation of an integer, the number of such operations that can be performed. Obviously, the number of cycles can be reduced.
Code:
#include "stdafx.h" #include <iostream> using namespace std; int CountOf1(int n) { int nCount = 0; while (n) { nCount++; n = n & (n -1); } return nCount; } int _tmain(int argc, _TCHAR* argv[]) { cout << CountOf1(7) << endl; system("pause"); return 0; } #include "stdafx.h"#include <iostream>using namespace std;int CountOf1(int n){int nCount = 0; while (n) {nCount++;n = n & (n -1); }return nCount;}int _tmain(int argc, _TCHAR* argv[]){cout << CountOf1(7) << endl; system("pause");return 0;}