How to wit to determine whether an integer is 2 n-th power

Source: Internet
Author: User

The beauty of programming-Microsoft technical Interview Experience the book details several methods that are of interest to see.

I'm only writing two methods that are easier to understand.

First Kind

2 10

4 100

8 1000

。。。。。

Found that the rule is not, 2 of the N-second side into the binary after the first 1, the rest of the bits are 0.

So, we can do this with the flattering, assuming the input is int:

Boolean powerof2 (int n)
{return
      ((n& (n-1)) ==0)
}

The second is to take this number to 2 modulo 0, and then divide 2, and then 2 modulo, until the number is finally 2, if you can't do this is not 2 of the N-Power. This method if not understand can take 56 of this number, to follow the process of their own calculation. We can understand the secret of this.

int count = 1;
while (i)
{
    if (2 = i)        //Note that the final Judgment of 2 is the key
    {
        System.out.println ("yes");  
        break;
    if (0 = = i%2)
    {
       i = I/2;
       Count + +;
     }
     else
     {
        System.out.print ("no");
        break;
      }
}


There are a lot of ways, we can go to divergent thinking.


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.