Power discrimination of 2

Source: Internet
Author: User

Turn | How to quickly determine whether a positive integer is a power of 2

Turn from past memory: http://www.iteblog.com/archives/716

The power of 2 has the following two characteristics:

1.20=1, 0001,21=2, 0010,22=4, 0100,23=8, 10,002, there is only one 1, and 1 followed by N 0.

2. If the number minus 1 will be found that the only 1 will become 0, and the original N 0 will become 1, so the original number and the number minus 1 after the operation will be found to 0 ((x & x-1) = = 0).

Reason: Because 2n conversion is binary 10 ... 0 in this form, the binary of the 2n-1 is 0111 ... 1, the two binary and the result is 0, for example: 16 of the binary is 10000;15=01111, the results of both phases are 0.

Therefore, the following algorithm can be used to determine whether a positive integer is a power of 2:

1 bool ispoweroftwo (int  x) {2     return x>0&&! ( x& (x1)); 3 }

Power discrimination of 2

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.