after the power of 4 is written in binary form, it is easy to find a feature:The binary has only one 1 (1 in odd position), and 1 followed by an even number of 0, so the question can be converted to determine whether 1 followed by an even number of 0.
4 of the integer power of the binary numbers are (4) 100, (16) 10000, (64) 1000000 ...
In addition, the power of the 4 square 4^n can also be written as 2^ (2*n), which can also be written as a power of 2, of course, to meet the power of 2 of the conditions, that is, Num & num-1==0.
Idea: First use conditional num & num-1==0 to judge whether the power of 2, if not satisfied, is not. If satisfied, in the condition of Num & 0x55555555 to judge, if true, then this integer is 4 power side, otherwise not.
the code that uses the recursive implementation is as follows:
Copy Code code as follows:
#include "stdio.h"
#include "Stdlib.h"
BOOL fn (unsigned int x)//Determine if x is a power exponent of 4
{
if (x & (X-1))//Judge whether X is 2 power square
return false;
return x & 0x55555555; To determine whether 1 is in an odd position.
}
int log4 (int value)//recursive judge how many times a number is 4
{
if (value = = 1)
return 0;
Else
{
value>>=1; Shift right.
Return 1+log4 (value>>1); Shift right.
}
}
int main (void)
{
int num;
printf ("Please enter an integer:");
scanf ("%d", &num);
if (FN (num))//use and operation to determine whether a number is a power square of 2
printf ("%d is 4%d Times Square!") \ n ", Num,log4 (num));
Else
printf ("%d is not a power party of 4!") \ n ", num);
System ("pause");
return 0;
}
The code that uses the non-recursive implementation is as follows:
Copy Code code as follows:
#include "stdio.h"
#include "Stdlib.h"
BOOL fn (unsigned int x)//Determine if x is a power exponent of 4
{
if (x & (X-1))//Judge whether X is 2 power square
return false;
return x & 0x55555555; To determine whether 1 is in an odd position.
}
int log4 (int value)//non-recursive judge how many times a number is 4
{
int x=0;
while (value>1)
{
value>>=1; Shift right.
value>>=1;
x + +;
}
return x;
}
int main (void)
{
int num;
printf ("Please enter an integer:");
scanf ("%d", &num);
if (FN (num))//use and operation to determine whether a number is a power square of 2
printf ("%d is 4%d Times Square!") \ n ", Num,log4 (num));
Else
printf ("%d is not a power party of 4!") \ n ", num);
System ("pause");
return 0;
}