---
title: 'LeetCode 326. Power of Three'
disqus: hackmd
---
# LeetCode 326. Power of Three
## Description
Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3^x^.
## Example
Input: n = 27
Output: true
Input: n = 0
Output: false
## Constraints
-2^31^ <= x <= 2^31^ - 1
## Answer
方法一,用while來除n直到n變成1為止,若其中有餘數就return false,若無餘數就return true。
```Cin=
//2021_11_30
bool isPowerOfThree(int n){
if(n > 0 && n & 1){
while(n != 1){
if(n % 3 != 0){return false;}
n /= 3;
}
return true;
}
return false;
}
```
X = log~3~n = log(n) / log(3),且3^X^ = n,若是3的次方數,則以log的整數取出X再做次方計算必為原n。
```Cin=
//2022_03_12
bool isPowerOfThree(int n){
float tmp = log(n)/log(3);
return n>0 && (pow(3,tmp) == n);
}
```
## Link
https://leetcode.com/problems/power-of-three/
###### tags: `Leetcode`