From: http://blog.csdn.net/hackbuteer1/article/details/6681157
After the power of 2 is written in binary form, it is easy to find that there is only one 1 in binary, and 1 followed by N 0; therefore, the problem can be converted to determining whether n zeros are followed by 1.
If we subtract this number from 1, we will find that the only one will change to 0, and the original N 0 will change to 1; therefore, the original number and the number after the first subtraction will be zero after calculation.
The fastest way:
(Number & number-1) = 0
Cause: Because the Npower of 2 is converted to binary 10 ...... 0 (except 0 ). And the number of digits-1 on the top. The result is 0. For example. The binary value of 8 is 1000, and the binary value of 8-1 = 7 is 111. The result of the two phases is 0. The calculation is as follows:
1000
&
0111
-------
0000
The Code implemented by recursion is as follows:
# Include "stdio. H "# include" stdlib. H "int log2 (INT value) // recursively judge the power of a number of 2 {If (value = 1) return 0; elsereturn 1 + log2 (value> 1);} int main (void) {int num; printf ("enter an integer:"); scanf ("% d ", & num); If (Num & (num-1) // use and calculate to determine whether a number is the power of 2 printf ("% d is not the power of 2! \ N ", num); elseprintf (" % d is the power of % d of 2! \ N ", num, log2 (Num); System (" pause "); Return 0 ;}
The Code implemented using non-recursion is as follows:
# Include "stdio. H "# include" stdlib. H "int log2 (INT value) // determines the power of a number of 2 in non-recursion {int x = 0; while (value> 1) {value >>=1; X ++;} return X;} int main (void) {int num; printf ("enter an integer:"); scanf ("% d", & num ); if (Num & (num-1) // use and calculate to determine whether a number is the power of 2 printf ("% d is not the power of 2! \ N ", num); elseprintf (" % d is the power of % d of 2! \ N ", num, log2 (Num); System (" pause "); Return 0 ;}