Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
这里可以用log的换底公式,logab = logb/loga。代码如下:
public class Solution {
public boolean isPowerOfThree(int n) {
double num = Math.log10(n) / Math.log10(3);
if (num % 1 == 0) {
return true;
} else {
return false;
}
}
}
这里如果用Math.log的话,测试集243结果是4.99999999,这跟计算机组成原理有关。
也可以用下面这个思路,
public class Solution {
public boolean isPowerOfThree(int n) {
// 1162261467 is 3^19, 3^20 is bigger than int
return ( n>0 && 1162261467%n==0);
}
}