This is an interview question I encountered during an interview yesterday.
It seems simple at first glance, but it just can’t be realized in the details.
After returning home, I searched on Baidu and found an answer.
It is as follows:
//计算一个十进制数转换为二进制数中‘1’的个数 //例如十进制11 = 二进制1011,则结果是3个1 //解题思路:利用 n & (n - 1) 可以将最后一个1变0 //xxxx1000 & (xxxx1000 - 1) = xxxx1000 & xxxx0111 = xxxx0000 // 1011 & (1011 - 1) = 1011 & 1010 = 1010 //直到最后一个1被与为0,得出结果 function count1($n) { $r = 0; while ($n != 0) { $r++; $n &= ($n - 1); } return $r; } echo count1(11);
After reading it, I think it is not very easy to understand (I am not good at bit operations...)
I thought about it for a while, and I 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 much easier to understand.
The above introduces a PHP interview question (calculating the number of '1's in a decimal number after converting it to binary), including relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.