Fast computing of 1 digits in 32 digits

Source: Internet
Author: User

A statement is used to determine whether X is a power of 2.

# Define is2 * n (x) (X & (X-1 ))? 0: 1)

Int main (void)

{

Int M = 512;

Cout <(M & (m-1 ))? False: True) <Endl;

// That is, when only one digit in M is 1, it is several power values.

// If there are two or more 1 s, the (M & (m-1) value is not 0, and the output value is 0, indicating that it is not several power of 2

Return (0 );

}

Analogy: The power of X 2 indicates that the number of digits of 1 in X is 1, and the question is converted to the number of digits of 1 in a 32-digit number. If it is 1, indicates several power pairs of 2.

Similarly, you can use this rule to calculate the number of 1 digits in a 32-digit number. (M & (m-1) can be used to remove one digit each time. The calculated number of times is the number of 1 digits.

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.