Easy
3241153FavoriteShare
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
Follow up:
Could you do it without using any loop / recursion?
循环除法:
C++ :
/*
* @Autor: SourDumplings
* @Date: 2019-09-10 20:21:54
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/power-of-three/
*/
class Solution
{
public:
bool isPowerOfThree(int n)
{
while (n > 1 && n % 3 == 0)
{
n /= 3;
}
return n == 1;
}
};
换底公式法1:
Java:
/*
* @Autor: SourDumplings
* @Date: 2019-09-10 20:32:57
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/power-of-three/
*
* 设3^i = n,则i = log3(n) = log10(n) / log10(3)
* 判断这样得到的3^i还是不是n,或者i是不是整数即可(用 % 1判断)
*/
class Solution
{
public boolean isPowerOfThree(int n)
{
return n != 0 && (Math.log10(n) / Math.log10(3)) % 1 == 0;
}
}
换底公式法2:
Java:
/*
* @Autor: SourDumplings
* @Date: 2019-09-10 20:32:57
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/power-of-three/
*
* 设3^i = n,则i = log3(n) = log10(n) / log10(3)
* 判断这样得到的3^i还是不是n,或者i是不是整数即可(用 % 1判断)
*/
class Solution
{
public boolean isPowerOfThree(int n)
{
if (n == 0)
return false;
int i = (int) (Math.log10(n) / Math.log10(3));
return Math.pow(3, i) == n;
}
}