### 231.  Power of Two



题目:

<https://leetcode.com/problems/power-of-two/>

难度:

Easy



思路：



power of two 那是这个数字的binary 表示一定只有一个1

套用以前的代码[leetcode191](https://github.com/Lisanaaa/thinking_in_lc/blob/master/191._number_of_1_bits.md)

这样会超时

```
class Solution(object):
    def isPowerOfTwo(self, n): # 此法超时
        """
        :type n: int
        :rtype: bool
        """
        cnt = 0
        while n != 0:
        	n &= n - 1
        	cnt += 1
        return cnt == 1
```



跟power of three一样递归，可以AC



```python
class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False
        if n == 1:
            return True
        if n % 2 == 0:
            return self.isPowerOfTwo(n/2)
        return False
                	
```







也是有[算法的wikipedia page](https://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two)

> The [binary representation](https://en.wikipedia.org/wiki/Binary_numeral_system) of integers makes it possible to apply a very fast test to determine whether a given [positive integer](https://en.wikipedia.org/wiki/Positive_integer) *x* is a power of two:
>
> positive *x* is a power of two ⇔ (*x* & (*x* − 1)) is equal to zero.



注意特殊case 0的处理

```python
class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n & (n-1) == 0 if n != 0 else False
```



