I was asked this question during the interview: it is not difficult to judge the number of 1 in a 32-bit unsigned integer binary. However, it requires optimization at different layers. Now let's sort it out:
1. Basic Ideas:
# Include <iostream>
Using namespace STD;
Int findone (unsigned int N ){
For (INT I = 0; n> 0; n> = 1)
I + = (N & 1 );
Return I;
}
Int main (){
Int N;
Cin> N;
Cout <findone (n) <Endl;
Return 0;
}
2. Optimization:
The time complexity is T (m) = m, depending on the number of digits of the binary number M. What should I do if I want to find it in a shorter time? If the findone function is repeatedly called (thousands of calls), how should we optimize it?
In fact, it is the idea of changing the space time: You can pre-create a table and store it from 0 ~ 2 ^ 32 indicates the number of 1 in each number. You can check the table when necessary. But this obviously takes a lot of space (at least 2 ^ 32/(256/32) = 512 MB, haha, it is the general memory size ). Therefore, optimization is required: store the number of 1 in each number from 0 to, and then perform segmented query. For example, the 32-digit table is divided into 4 segments, each segment contains one byte, so there is a 256-bit table for query:
Char tone [256] = "\ 0 \ 1 \ 1 \ 2 \ 1 \ 2 ...... "; // Unspecified
Int findone (unsigned int N ){
For (INT I = 0; n> 0; n> = 8)
I + = tone [N & 255];
Return I;
}
3. It is said that intel has an assembly command (or several) to complete this work, but it does not know what it is and how it should be done.
4. You can see the same things in youdao MS:
Int func (unsigned int N ){
Int COUNT = 0;
While (n> 0 ){
N & = (n-1 );
Count ++;
}
Return count;
}