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

# Power of Three

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

> 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?

## Thoughts

如果是3的power, 那么能一直/3一直到 1且每次除后的数和3取余都为0.

## Code

```
class Solution {
    public boolean isPowerOfThree(int n) {
        while (n > 1) {
            if (n % 3 != 0) {
                return false;
            }
            n = n / 3;
        }

        return n == 1 ? true : false;
    }
}
```

## Analysis

时间复杂度是O(lgn).

## Ver.2

我们可以找到MaxPow(3)最大能取到的数, 给定的N如果是3的倍数, 那么MaxPow(3) % N == 0.

```
class Solution {
    public boolean isPowerOfThree(int n) {
        return n > 0 && 1162261467 % n == 0;
    }
}
```
