This is yesterday to interview, met a face question.
At first glance it's pretty simple, but it's not in the details.
After home Baidu, find an answer.
As follows:
To calculate the number of ' 1 ' in a decimal number converted to a binary number//For example, decimal 11 = binary 1011, the result is 3 1 //Solving ideas: Use N & (n-1) To change the last 1 to 0 //xxxx1000 & (xxxx1 000-1) = xxxx1000 & xxxx0111 = xxxx0000 //1011 & (1011-1) = 1011 & 1010 = 1010 //Until the last 1 is associated with 0, results are obtained function Count1 ($n) { $r = 0; while ($n! = 0) { $r + +; $n &= ($n-1); } return $r; }
After looking at it is not very easy to understand (my bit of computational science is not good ...) )
Think for a moment, have the following solution:
function Count1 ($n) { $r = 0; while ($n!=0) {if (($n%2)!=0) {$r + +;} $n = $n/2; } return $r;} Echo Count1 (8);
This should be easier to understand.
The above introduces the PHP surface of the test together (calculate the number of a decimal number to binary after the ' 1 '), including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.