Given an integer, write a function to determine if it is a power of.
Hint:
- Could you solve it in O (1) time and using O (1) space?
This problem lets us judge whether a number is 2, and requires time and space complexity are constant, then for this kind of play number problem, we should first consider bit to operate bit operation. In the Leetcode, there are many problems with the bit operation, such as repeated DNA sequences to repeat the DNA sequence, single number alone, single number II separate numbers two, Grey code Gray Code, Reverse bits Flip bit, Bitwise and of Numbers range digit range bit phase, number of 1 bits bit 1 and Divide two integers two divide, etc. So let's look at the characteristics of the binary notation for the next 2 of the number of squares:
1 2 4 8 16 ....
1 10 100 1000 10000 ....
Then we can easily see that 2 of the number of times there is only one 1, the rest is 0, so we have the idea of solving the problem, we just want to determine whether the lowest bit is 1, and then shift to the right, the last count 1 of the number can determine whether it is 2 of the number of times, the code is as follows:
Solution One:
class Solution {public: bool ispoweroftwo (int n) { int 0; while 0 ) { 1); 1 ; } return 1 ; } };
There's a trick to this problem, if a number is 2, according to the above analysis, then its binary number is necessarily the highest bit is 1, the other is 0, then if we subtract 1 at this time, then the highest bit will drop one, the other 0 of the bit is now changed to 1, then we will two number and, we'll get 0, With this nature can also be solved, and just a line of code can be done, as follows:
Solution Two:
class Solution {public: bool ispoweroftwo (int n) { Return01))); } };
[Leetcode] Power of two judges 2 of the number of times