# [LeetCode] Power of Three 判断3的次方数

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 打赏
posted @ 2016-01-18 06:41  Grandyang  阅读(18025)  评论(10编辑  收藏  举报