Turn | How to quickly determine whether a positive integer is a power of 2
Turn from past memory: http://www.iteblog.com/archives/716
The power of 2 has the following two characteristics:
1.20=1, 0001,21=2, 0010,22=4, 0100,23=8, 10,002, there is only one 1, and 1 followed by N 0.
2. If the number minus 1 will be found that the only 1 will become 0, and the original N 0 will become 1, so the original number and the number minus 1 after the operation will be found to 0 ((x & x-1) = = 0).
Reason: Because 2n conversion is binary 10 ... 0 in this form, the binary of the 2n-1 is 0111 ... 1, the two binary and the result is 0, for example: 16 of the binary is 10000;15=01111, the results of both phases are 0.
Therefore, the following algorithm can be used to determine whether a positive integer is a power of 2:
1 bool ispoweroftwo (int x) {2 return x>0&&! ( x& (x1)); 3 }
Power discrimination of 2