Php interview questions (calculate the number of '1' after a decimal number is converted to binary)

Source: Internet
Author: User
: 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.

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.