The beauty of programming: 2.1 calculate the number of 1 in the binary number

Source: Internet
Author: User

Suppose there are n

In the past, logn used the division of two remainder methods to describe the complexity of logn.

There is a logv method where the number of V is 1 is less complex than logn.

 

int Count(int x){int ans = 0;while(x){x &= (x-1);ans++;}return ans;}


Here we use the bitwise Operation X & (x-1) to remove one at a time.

100010001000 & (100010001000-1) = 100010000000

100010000000 & (100010000000-1) = 100000000000

100000000000 & (100000000000-1) = 000000000000

Remove 1 at a time three times in total

 

Then add

for(int i = s; i; i = (i-1)&s)

This loop enumerates all the subsets of S, for example, S = 10101.

10101-> 10100-> 10001-> 10000-> 00101-> 00100-> 00001-> 00000

In this way, all the subsets of S are enumerated.

This will be used when the status is compressed to DP

 

 

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.