1. Brief Introduction
For an unsigned integer variable of a byte (8 bit), the binary value indicates the number of "1", and the algorithm execution efficiency is as high as possible.
2. Ideas
I have no new discoveries on this question, that is, I will talk about the solution to the beauty of programming. The first thought is a single-digit judgment. The eight-digit number is eight times. The second approach is to reduce the last 1 in the binary number until the number changes to 0. This method is only related to the number of 1 in the binary number, so it is a little more complex than the first idea, each time the method of reducing the last 1 is num = num & (num-1 ).
3. Code
#include <iostream>
using namespace std;
unsigned char find_num_method_1(char num) {
unsigned char count = 0;
for(int i=0; i<8; i++) {
count += num & 0x01;
num >>= 1;
}
return count;
}
unsigned char find_num_method_2(char num) {
unsigned char count = 0;
while(num > 0) {
count++;
num = num & (num-1);
}
return count;
}
int main() {
char num;
cin >> num;
cout << (int)find_num_method_1(num) << endl;
cout << (int)find_num_method_2(num) << endl;
system("PAUSE");
return 0;
}
Output result:
4. scaling problems
First extension: If the variable is a 32-bit DWORD, which method will you use or improve?
Second extension: two positive integers (expressed in binary form) A and B are given. How many digits do I need to change A to B? That is to say, how many bits are different in the binary representation of A and B?
For the first extension, it cannot be used to create a table. A 32-bit DWORD table requires 2 ^ 32 (that is, 4 GB) numbers. Each number is a byte, which requires a total of 4 GB. However, it is okay to use the two methods mentioned in section 3. the maximum number is 32.
For the second extension, A and B are exclusive OR, and then the number of 1 in the result of this exclusive or is obtained.
5. Reference
The beauty of programming, section 2.1, calculates the number of 1 in binary.