Determines whether a number is 2 of the n-th power

Source: Internet
Author: User

Reference: http://bbs.csdn.net/topics/370058619

Title, how to Tell if an integer is 2 n times, I can think of a method that has two

1. Always except 2, see if the last equals 1. (The Dumbest method)

2. Convert to 2 to see if it looks like this: 1,10,100,1000,10000, except the highest bit is 1, the others are 0, or only one 1.

3. When I was complacent about the second method I could think of, I saw the more ingenious way

1234567 4(100)    7(0111)    8(1000)为例43--> 100011076--> 01110110!= 087--> 100001110即 如果 m & (m - 1) == 0,则m是2的n次方。

  

123 publicstatic boolean fun(int i){    return(i > 0) && ((i & (i - 1)) == 0);}

Determines whether a number is 2 n power

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.