After the power of 4 is written in binary form, it is easy to find that there is only one 1 in binary (1 in the odd position), and 1 followed by an even number of 0; therefore, the problem can be converted to determining whether an even number of zeros is followed by 1.
The binary number of the integer power of 4 is (4) 100, (16) 10000, (64) 1000000 ......
In addition, the power of 4 4 ^ n can also be written to 2 ^ (2 * n), that is, it can also be written to the power of 2, of course, to meet the power of 2 conditions, that is, num & num-1 = 0.
Idea: first use the condition num & num-1 = 0 to determine whether it is the power of 2, if not met, it is not. If this condition is met, num & 0x55555555 is used as the condition. If it is true, the integer is the power of 4. Otherwise, it is not.
The Code implemented by recursion is as follows:
# Include "stdio. H "# include" stdlib. H "bool FN (unsigned int X) // determines whether X is 4 to the power {If (X & (X-1 )) // determine whether X is 2 to the power return false; return X & 0x55555555; // determine whether 1 is at an odd position} int log4 (INT value) // recursively determine the power of a number of 4 {If (value = 1) return 0; else {value> = 1; // shift to the right return 1 + log4 (value> 1); // shift to the right} int main (void) {int num; printf ("enter an integer: "); scanf (" % d ", & num); If (FN (Num )) // use and calculate to determine whether a number is the power of 2 printf ("% d is the power of 4% d! \ N ", num, log4 (Num); elseprintf (" % d is not the power of 4! \ N ", num); System (" pause "); Return 0 ;}
The Code implemented using non-recursion is as follows:
# Include "stdio. H "# include" stdlib. H "bool FN (unsigned int X) // determines whether X is 4 to the power {If (X & (X-1 )) // determine whether X is 2 to the power return false; return X & 0x55555555; // determine whether 1 is at an odd position} int log4 (INT value) // non-recursive determination of the power of a number of 4 {int x = 0; while (value> 1) {value> = 1; // shift value> = 1; X ++;} return X;} int main (void) {int num; printf ("enter an integer :"); scanf ("% d", & num); If (FN (Num )) // use and calculate to determine whether a number is the power of 2 printf ("% d is the power of 4% d! \ N ", num, log4 (Num); elseprintf (" % d is not the power of 4! \ N ", num); System (" pause "); Return 0 ;}