PHP Face Test (calculates the number of ' 1 ' after a decimal number goes into binary)

Source: Internet
Author: User


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.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.