# Judge whether an integer is the integer power of 2-A pen question of Xiaomi

Source: Internet
Author: User

# Include <iostream>

Using namespace STD;

// The first method exploits the loop
Bool makedemo-( const Int & M, Int & POW) // POW indicates how many power m is 2
{
Int I = 2;
Int S = 1;
Pow = 0;
If (M <0) return false;
If (M = 0) return true;
Do
{
S * = I;
Pow ++;
} While (S <m );
If (S = m) return true;
Else
{
Pow = 0;
Return false;
}
}

// The second method. If M/2 is the integer power of 2, m is the integer power of 2. Recursive Implementation
Bool makedemo-( int M, int * POW)
{
If (M <0) return false;
If (M % 2! = 0) return false;
If (M = 0) return true;
Else if (M = 2)
{
* POW = * POW + 1;
Return true;
}
Else
{
* POW = * POW + 1;
Makedemo-( M/2, pow );
}
}

// An integer that is an integer power of 2. Its value ranges from 0 to 1, 2... all are 1, and the rest are 0. In this way, the position of-M's complement code is the same as that of M's complement Code 1.
// Therefore, M &-M is m
Bool makedemo-( Int & M)
{
Return M = (M & (-m ));
}

Void main ()
{
Cout <"enter an integer greater than 0 :";
Int m;
Cin> m;
Int POW = 0;
// If (makedemo-( M, & POW) cout <m <"is 2" <POW <"power" <Endl;
If (makedemo-( m) cout <m <"is an integer power of 2" <Endl;
Else cout <m <"is not an integer power of 2! "<Endl;
}

Related Keywords:

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.