: This article mainly introduces a php interview question (calculate the number of '1' after a decimal number is converted to binary number). If you are interested in the PHP Tutorial, refer to it. Zookeeper
This is an interview question I encountered yesterday.
At first glance, it is quite simple, but it cannot be implemented in detail.
After returning home, Baidu found an answer.
As follows:
// Calculate the number of '1' in a decimal number and convert it to binary number. // for example, if decimal 11 = binary 1011, the result is 3 1. // solution: use n & (n-1) to change the last 1 to 0 // xxxx1000 & (xxxx1000-1) = xxxx1000 & xxxx0111 = xxxx0000 // 1011 & (1011-1) = 1011 & 1010 = 1010 // until the last 1 is 0, the result is: 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 easy to understand (my bit operations are not good at learning ...)
I thought about the solution below:
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 section describes the php interview questions (calculate the number of '1' after a decimal number is converted to binary), including the content, and hope to help friends who are interested in the PHP Tutorial.