Determines whether an unsigned number is 2 of the N-Power form

Source: Internet
Author: User
This is a question to ask in the interview. Can first analyze 2 of the number of N power form, the second binary form must be only 1bit is 1, the remaining bit is 0
So an intuitive approach is to compare all 2 of the N powers, since the unsigned integer we typically consider is 32 bits, so there are 32 2 of the N power (can be obtained by moving 1 left 0 to 31 bits). This method needs to be shifted and compared 32 times in the worst case, which is less efficient.
A closer analysis can be found that 2 of the number of power form N, the second binary form of 0 ... 010...0, assuming that after 1 there is an I 0 (0<=i<=31), then this number minus 1 will appear at the end of a continuous number I 1. For example, binary number 0100, this number minus 1 equals 0011, the two number is 0
Therefore, a more optimal algorithm is:
inline bool is2n (unsigned int i)
... {
if (i==0) return false;
else return (i& (i-1)) ==0;
}

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.