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?
方法一:由于是int范围,在int范围内最大的3次方数为 3^19 = 1162261467。故直接用它对3求余即可。注意判断n的条件。
class Solution {
public boolean isPowerOfThree(int n) {
return (n>0 && 1162261467 % n ==0);
}
}
方法二:
下面的方法是我在讨论区里看到的一种比较有意思的方法。该方法先将数字转换为三进制的字符串,再用正则10*(意为1后面跟0个或n个0)匹配算出结果。
Java代码如下:
/**
* @功能说明:LeetCode 326 - Power of Three
* @开发人员:Tsybius2014
* @开发时间:2016年1月11日
*/
public class Solution {
/**
* 判断数字是否为3的幂
* @param n
* @return
*/
public boolean isPowerOfThree(int n) {
if (n <= 0) {
return false;
} else {
return Integer.toString(n, 3).matches("10*");
}
}
}
方法三:利用log3(n)= loge(n)/loge(3)。当时当n=243的时候会有问题(等于4.999999999),所以要转化为底数为10。但是在java里面还是有问题。最稳妥的方案是直接求出所成次幂,然后用round函数求整(假设为x),再计算3^x是否等于n。
class Solution {
public boolean isPowerOfThree(int n) {
double res = Math.log(n)/Math.log(3);
return n>0 && (Math.pow(3,Math.round(res)) == n);
}
}