# 326. Power of Three

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

Example 1:

``````Input: 27
Output: true
``````

Example 2:

``````Input: 0
Output: false
``````

Example 3:

``````Input: 9
Output: true
``````

Example 4:

``````Input: 45
Output: false
``````

Could you do it without using any loop / recursion?

``````class Solution {
public:
bool isPowerOfThree(int n) {
while (n && n % 3 == 0) {
n /= 3;
}
return n == 1;
}
};
``````

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

``````class Solution {
public:
bool isPowerOfThree(int n) {
return (n > 0 && int(log10(n) / log10(3)) - log10(n) / log10(3) == 0);
}
};
``````

Power of Two

Power of Four

https://leetcode.com/problems/power-of-three

https://leetcode.com/problems/power-of-three/discuss/77856/1-line-java-solution-without-loop-recursion

https://leetcode.com/problems/power-of-three/discuss/77876/**-A-summary-of-all-solutions-(new-method-included-at-15%3A30pm-Jan-8th)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation