Solve the number of 1 in the binary number

Source: Internet
Author: User

This question has appeared in many tests. I took the test in Alibaba last year and got the test. The beauty of programming is also mentioned. A better method is bit-wise. The solution is as follows:

Execute X & (X-1), set the rightmost 1 to 0, know that the last X is changed to 0, and the cycle ends. The time complexity is O (m ), M is the number of 1 in the binary number.

Another solution is that the time complexity is log (N), where N is the total number of digits of the binary number.

# Include <stdio. h> int main () {unsigned int x = 0 xffffffff; X = (X & 0x55555555) + (x> 1) & 0x55555555 ); // 01010101 x = (X & 0x33333333) + (x> 2) & 0x33333333); // 00110011 x = (X & 0x0f0f0f) + (x> 4) & 0x0f0f0f); // 00001111 x = (X & 0x00ff00ff) + (x> 8) & 0x00ff00ff ); // 0000000011111111 x = x + (x> 16); printf ("% d \ n", X & 0x0000003f); Return 0 ;}

Core Ideas:

The number of bits and bits is counted. The value is stored in the value until it is finally merged into a value, which is the total number of 1.

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.