> For the complete documentation index, see [llms.txt](https://rachel2011.gitbook.io/leetcode_cc150/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://rachel2011.gitbook.io/leetcode_cc150/leetcode/power-of-three.md).

# Power of Three

Given an integer, write a function to determine if it is a power of three.

**Follow up:**\
Could you do it without using any loop / recursion?

最直接的方法就是不停地除以3，看最后的余数是否为1，要注意考虑输入是负数和0的情况

Time complexity :O(log\_b(n))O(log​b​​(n)). In our case that isO(log\_3n)O(log​3​​n). The number of divisions is given by that logarithm.

* Space complexity :O(1)O(1). We are not using any additional memory.

```
class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        while n%3 == 0 and n:
            n = n/3
        if n == 1:
            return True
        return False
```

![](https://4287834316-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LrHZbp0PteFRD1_lznR%2F-LrHZcENYxC8MDIjVGwU%2F-LrHZiz3UWDp6A5LGAN1%2F123.png?generation=1571195909438335\&alt=media)<https://discuss.leetcode.com/topic/33536/a-summary-of-all-solutions-new-method-included-at-15-30pm-jan-8th/2>

```
class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n > 0 and (math.log10(n)/math.log10(3))%1==0
```

最后一直方法是recursion：

```
class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n == 1:
            return True
        if n == 0 or n % 3 > 0:
            return False
        return self.isPowerOfThree(n / 3)
```
