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

Source: Internet
Author: User
Tags decimal to binary

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

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

 

 


1 In the binary number

This method should be relatively simple when we use Shift and one-digit retrieval and judgment. In addition, it can be calculated based on the decimal to binary algorithm. Another way is to format it into a string in the form of % B, so that the binary number becomes a string and can be judged one by one.

1 In the binary number

Change printf and scanf by yourself, so you can become lazy IFU.

# Include <stdio. h>
Void main ()
{
Int n;
Scanf ("% d", & n );
Int nCount = 0;
For (; n! = 0; n = n> 1)
If (n & 1)
++ NCount;
Printf ("% d", nCount );
}

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.