Home  >  Article  >  Backend Development  >  PHP interview question (calculate the number of ‘1’s in a decimal number after converting it to binary)

PHP interview question (calculate the number of ‘1’s in a decimal number after converting it to binary)

WBOY
WBOYOriginal
2016-08-08 09:22:42975browse



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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn